Skip to content

Instantly share code, notes, and snippets.

@prestongarno
Last active May 19, 2018 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prestongarno/6d399dd00a03734b69b24121ed9bae8d to your computer and use it in GitHub Desktop.
Save prestongarno/6d399dd00a03734b69b24121ed9bae8d to your computer and use it in GitHub Desktop.
What is the output of this program?
import kotlin.reflect.KProperty
class ResponsibleDelegate<out T>(initializer: () -> T?) {
private val value by lazy(initializer)
operator fun getValue(thisRef: Any?, property: KProperty<*>): T =
value ?: throw NullPointerException()
}
class CarelessDelegate<out T>(initializer: () -> T?) {
private val value by lazy(initializer)
operator fun getValue(thisRef: Any?, property: KProperty<*>): T =
value as T
}
fun main(args: Array<String>) {
val definitelyNotNull by ResponsibleDelegate { 10 }
val definitelyNull by CarelessDelegate<Int> { null }
val values = mutableListOf<Int>()
try {
values += definitelyNotNull
values += definitelyNull
} catch (ex: NullPointerException) {
values += 20
}
println("Result: $values")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment