Last active
May 19, 2018 17:57
-
-
Save prestongarno/6d399dd00a03734b69b24121ed9bae8d to your computer and use it in GitHub Desktop.
What is the output of this program?
This file contains 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
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