Kotlin - How to reproduce the effect of "lateinit" on a "var" of an interface?

1

I have an interface called UserManager which has a var of type User

interface UserManager {

    var user:User

    /* ... */
}

and a class named UserManagerImpl that implements UserManager

class UserManagerImpl : UserManager {

    override var user: User // = uma instancia default de User deve ser fornecida

    /* ... */
}

My question is as follows

How to allow a class to set a User in UserManager() at any time (* ie * I would not provide a User default ), but would leave that another class would create and select a User when needed)?

Notes

  • Interfaces do not have lateinit properties
  • I would like the User class to be not null , so I did not want null to be the default value for user ie doing var user: User? = null )
  • I would like to access the fields directly rather than using interface methods ( i.e ) to call userManager.user to return a user, rather than userManager.getUser ())
  • asked by anonymous 21.04.2016 / 00:32

    1 answer

    1

    You can not really set a lateinit property on an interface.

    But you can set this property to lateinit in the subclass.

    It would look something like:

    interface UserManager {
        var user: User
    }
    
    class UserManager Impl: UserManager {
        override lateinit var user: User
    
        fun initUser(): UserManager = apply { user = User() }
    }
    
    println("${UserManagerImpl().initUser().user}")
    

    It will generate the result you want.

    Another alternative would be to use delegated properties with lazy , but this will force the property to be immutable, but it may serve you in another context:

    interface UserManager {
        val user: User
    }
    
    class UserManager Impl: UserManager {
        override val user: User by lazy {
            User()
        }
    }
    
    println("${UserManagerImpl().user}")
    
        
    21.04.2016 / 03:57