https://kotlinlang.org logo
#announcements
Title
# announcements
s

Simon Craigie

11/29/2019, 4:55 PM
hey all! Is there a way to create behaviour such as this without casting? I read that you can avoid unchecked cast exceptions with reified types but i can't seem to find a way to do this with function parameters:
Copy code
fun <PARENT, CHILD: PARENT> returnFuncWithParentTypeAsParameter(resolver: (CHILD) -> Unit): (PARENT) -> Unit {
            return resolver as (PARENT) -> Unit
        }
Thanks in advance!
a

Adam Powell

11/29/2019, 5:07 PM
What are you trying to do this for? This looks like an unsafe operation by definition unless you're planning to verify elsewhere that the parameter is of type
CHILD
when you call the resulting function.
s

Simon Craigie

11/29/2019, 5:22 PM
The resulting function will only ever be called with a
PARENT
object. If all
CHILD
's are of type
PARENT
's then is it still unsafe?
r

Robert Jaros

11/29/2019, 5:23 PM
Copy code
inline fun <PARENT, reified CHILD: PARENT> returnFuncWithParentTypeAsParameter(crossinline resolver: (CHILD) -> Unit): (PARENT) -> Unit {
    return {
        if (it is CHILD) {
        	resolver(it)
        }
    }
}
This seems safe, has no cast and even works ;)
a

Adam Powell

11/29/2019, 5:26 PM
The reason it's unsafe without the explicit filtering @Robert Jaros demonstrated above is because while all `CHILD`s are of type
PARENT
, all `PARENT`s are not of type
CHILD
. If you pass any
PARENT
to a
resolver
that is expecting parameters of type
CHILD
, you are trying to make the latter assertion, which cannot hold.
s

Simon Craigie

11/29/2019, 5:36 PM
ah of course. Thanks for clearing that up guys!
2 Views