Matej Drobnič
11/09/2020, 11:35 AMString
* in T
means that I can pass T or any of its super classes
* Any
is superclass of String
* so Container<in T>
should accept Container<Any>
right?
Instead I get:
Type mismatch.
Required :String
Found: Any
Matej Drobnič
11/09/2020, 11:44 AMMatej Drobnič
11/09/2020, 11:44 AMContainer<? super T>
which means T
or any of its super classes, right?kralli
11/09/2020, 12:00 PMT
is defined as T : Any?
. So the Container
might contain nullable types, methodB
only takes non-null types. You either have to bind T
as T : Any
or change methodB
to allow for nullable types fun methodB(input: Container<Any?>)
.kralli
11/09/2020, 12:02 PMfun <T : Any> methodA(target: (Container<T>) -> Unit)
would be another option.Animesh Sahu
11/09/2020, 12:04 PMmethodA<Any>(::methodB)
Animesh Sahu
11/09/2020, 12:05 PMAnimesh Sahu
11/09/2020, 12:07 PMkralli
11/09/2020, 12:23 PMdata class Container<T>(val value: T)
fun methodB(input: Container<Any>) {}
fun <T : Any> methodA(target: (Container<T>) -> Unit) {}
fun main() {
methodA(::methodB)
}
Matej Drobnič
11/09/2020, 12:23 PMMatej Drobnič
11/09/2020, 12:24 PMdata class Container<T: Any>(val value: T)
fun methodB(input: Container<Any>) {
}
fun <T : Any> methodA(target: (Container<in T>) -> Unit) {
}
fun main() {
methodA<String>(::methodB)
}
kralli
11/09/2020, 12:28 PM<in T>
and let the compiler do the inference in the main method by removing the explicit type definition.kralli
11/09/2020, 12:28 PMMatej Drobnič
11/09/2020, 12:33 PMin T
removes the whole idea of this exampleMatej Drobnič
11/09/2020, 12:34 PM<String>
here explicitly just to make example more conciseMatej Drobnič
11/09/2020, 12:36 PMdata class Container<T: Any>(val value: T)
fun methodB(input: Container<Any>) {
}
fun <T : Any> methodA(target: (Container<in T>) -> Unit, classOfT: Class<T>) {
}
fun main() {
methodA(::methodB, String::class.java)
}
kralli
11/09/2020, 12:41 PMdata class Container<T : Any>(val value: T)
fun methodB(input: Container<out Any>) {}
fun <T : Any> methodA(target: (Container<T>) -> Unit, classOfT: Class<T>) {}
fun main() {
methodA(::methodB, String::class.java)
}
Matej Drobnič
11/09/2020, 12:46 PMMatej Drobnič
11/09/2020, 12:46 PM