Last active
June 17, 2020 06:58
-
-
Save marcouberti/5760833d4c34c05ded7254d979b65e86 to your computer and use it in GitHub Desktop.
Alternative lateinit implementation without using the native lateinit Kotlin declaration.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyTest { | |
lateinit var subject: TestSubject | |
@SetUp fun setup() { | |
subject = TestSubject() | |
} | |
@Test fun test() { | |
subject.method() // dereference directly | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LateInit<T>() { | |
private var value: T? = null | |
fun set(_value: T) { | |
value = _value | |
} | |
fun get(): T { | |
return value ?: throw UninitializedPropertyAccessException() | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// declaration | |
val user = LateInit<User>() | |
// cannot use it before initialisation | |
user.get() // UninitializedPropertyAccessException | |
fun onCreate() { | |
// initialisation | |
user.set(User(name = "Marco")) | |
// now you can safely use it | |
user.get() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment