I am learning Kotlin. My code is as follows:
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
decoupler.attachNotifier(this)
if(activity is ScreenRouter) {
decoupler.attachRouter(activity)
}
}
attachRouter()
method:
fun attachRouter(router: ScreenRouter?) {
this.router = router
}
As written in documentation, kotlin automatically casts to type after checking with is operator. So, I expected that it would work. But instead it bothers me with compilation error saying :
Smartcast to ScreenRouter
is impossible because activity
is a property that has open or custom getter.
I thought maybe error is because activity can be nullable so I tried:
if(activity!=null && activity is ScreenRouter) {
decoupler.attachRouter(activity)
}
But it didn't work and compilation failed with same error.
However, following code works fine:
if(activity is ScreenRouter) {
decoupler.attachRouter(activity as ScreenRouter)
}
Its okay but above error doesn't seem to explain anything about why smartcast fails. I am not a Kotlin expert, I'm just a beginner learning Kotlin. I found no documentation anywhere. These kind of error descriptions makes Kotlin horrible to learn. Can anyone explain in simple terms?
remember
. Anything returned byremember
is not "smart cast"able anymore. But this can be solved, by creating a copy of the remembered value. The copied value can be "smart cast"ed. – Curmudgeon