Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

field

kotlin

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
like image 257
regmoraes Avatar asked Apr 20 '16 21:04

regmoraes


1 Answers

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.

like image 131
mfulton26 Avatar answered Oct 22 '22 05:10

mfulton26