Shan
03/24/2019, 7:42 AMas
but I couldn't get it to work, probably doing it wrong. My use-case:Czar
03/24/2019, 7:45 AMwhen
into an extension property, e.g. deviceScope
. That way when
will still be there but you won't have to repeat yourself.Shan
03/24/2019, 7:48 AMCzar
03/24/2019, 8:02 AMopen class Scope
class DeviceScope(val name: String) : Scope()
open class Fragment {
val scope: Scope = DeviceScope("Example device scope")
}
val Fragment.deviceScope: DeviceScope
get() {
check(scope is DeviceScope) {
"Non-DeviceScope scopes are not allowed"
}
return scope
}
class MyFragment : Fragment() {
init {
println(deviceScope.name)
}
}
SiebelsTim
03/24/2019, 8:13 AMscope as DeviceScope
should work as well. I don't know why it wouldn't work for you.Shan
03/24/2019, 8:15 AMCzar
03/24/2019, 8:17 AMclass MyFragment : Fragment() {
init {
(scope as DeviceScope).name
}
}
This works but is again repetitive.
You could combine both to avoid it:
val Fragment.deviceScope: DeviceScope
get() = scope as DeviceScope
class MyFragment : Fragment() {
init {
deviceScope.name
}
}
I would leave my original one though with the check(){}
, I think that makes the intent more obvious.Shan
03/24/2019, 8:21 AMas
. I was setting it to a value val deviceScope = scope as DeviceScope
which was throwing a NPE... for reasons I'm still not sure I understand. When I use it like (scope as DeviceScope).name
it works fine. I will probably make extension functions for Fragment class though as that is quite handy.Hamza
03/24/2019, 10:56 AMLeoColman
03/24/2019, 4:09 PM