regmoraes
regmoraes

Reputation: 5489

Kotlin - How to "lateinit" a var overrided from an interface?

I have an interface called UserManager

interface UserManager {

    var user:User

    /* ... */
}

and a class called UserManagerImpl, that implements the UserManager

class UserManagerImpl : UserManager {

    override var user: User // = must provide an User object

    /* ... */
}

Here's my problem:

How to allow another class to set an User in the UserManager() at any time ( i.e don't provide an initial User object alongside the property declaration and let another class create and provide an User instance) ?

Take in count that

  1. Interfaces cannot have lateinit properties
  2. I want the User to be a non-null value, so no nullable property ( User? )
  3. I want to use field access instead of declare and use a setUser(User) and getUser() method in the interface

Upvotes: 10

Views: 4400

Answers (1)

mfulton26
mfulton26

Reputation: 31214

It is true that "interfaces cannot have lateinit properties" but that doesn't prevent implementing classes from using it:

interface User

interface UserManager {
    var user: User
}

class UserManagerImpl : UserManager {
    lateinit override var user: User
}

fun main(args: Array<String>) {
    val userManager: UserManager = UserManagerImpl()
    userManager.user = object : User {}
    println(userManager.user)
}

Prints something like LateinitKt$main$1@4b1210ee.

Upvotes: 18

Related Questions