oh, I just realised the code above is fine, the re...
# announcements
d
oh, I just realised the code above is fine, the reason is that my code uses a function, not just the value
Copy code
sealed class Parent() {
    data class Child(val value: String) : Parent()
}
data class Other(val value: (Parent) -> String)
val child = Child("something")
val f: (Child) -> String = { child -> child.value}
val x = Other(f as (Parent) -> String)
đź§µ 3
d
Yes, the function expects a
Child
. You are casting it to something that expects a
Parent
, so someone could pass in an
Other
to your casted function - which would make that casted function fail.
d
I don’t quite understand, in what situation could this fail?
any function who’s input is a subtype of Parent wouldn’t fail
d
If
Parent
had more than one child:
x.value(Parent.Child2())
Now the function fails, because it assumes it gets a
Child
, not a
Child2
d
aahhh
got it thanks
d
Look up covariant vs. contravariant vs. invariant
d
I understand it, I just didn’t see it
it’s obvious now, thanks!