Skip to content

Instantly share code, notes, and snippets.

@marcouberti
Last active June 17, 2020 06:58
Show Gist options
  • Save marcouberti/5760833d4c34c05ded7254d979b65e86 to your computer and use it in GitHub Desktop.
Save marcouberti/5760833d4c34c05ded7254d979b65e86 to your computer and use it in GitHub Desktop.
Alternative lateinit implementation without using the native lateinit Kotlin declaration.
class MyTest {
lateinit var subject: TestSubject
@SetUp fun setup() {
subject = TestSubject()
}
@Test fun test() {
subject.method() // dereference directly
}
}
class LateInit<T>() {
private var value: T? = null
fun set(_value: T) {
value = _value
}
fun get(): T {
return value ?: throw UninitializedPropertyAccessException()
}
}
// 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