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

Asked

Viewed 131 times

1

I have an interface called UserManager who owns a var of the kind User

interface UserManager {

    var user:User

    /* ... */
}

and a class called UserManagerImpl implementing UserManager

class UserManagerImpl : UserManager {

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

    /* ... */
}

My question is this:

How to allow a class to set one User in the UserManager() at any time (* ie * I would not provide a User default, but let another class create and setasse one User when necessary) ?

Remarks

  1. Interfaces have no properties lateinit
  2. I’d like the class User were nonzero, so I didn’t want null is the default value for user (i and. making var user: User? = null )
  3. I would like to access the fields directly instead of using interface methods (i and. call userManager.user to return a user, rather than userManager.getUser() )

1 answer

1


It is really not possible to define a property lateinit in an interface.

But it is possible to define this property as 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}")

Will generate the result you want.


Another alternative would be to use properties delegated with lazy, but this will require 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}")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.