hey all! Is there a way to create behaviour such ...
# announcements
s
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
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
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
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
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
ah of course. Thanks for clearing that up guys!