zkeme
08/06/2020, 1:27 PMfun <T : Any> getFoo(defaultValue: T): Foo<T> {
return when (defaultValue) {
is Long -> LongFoo(defaultValue) as Foo<T> //LongFoo extends Foo<Long>
is Int -> IntFoo(defaultValue) as Foo<T> //IntFoo extends Foo<Int>
is String -> StringFoo(defaultValue) as Foo<T> //StringFoo extends Foo<String>
else -> NonPrimitiveFoo(defaultValue, defaultValue.javaClass)
}
}streetsofboston
08/06/2020, 1:31 PMFoo<T>, but you can do it only once instead of within each when-branch:
return when (defaultValue) {
...
} as Foot<T>zkeme
08/06/2020, 1:31 PMNicholas Bilyk
08/06/2020, 2:48 PMfun main(args: Array<String>) {
foo(3)
foo(true)
}
data class Foo<T>(val v: T)
fun foo(v: Int): Foo<Int> = Foo(v)
fun foo(v: Boolean): Foo<Boolean> = Foo(v)streetsofboston
08/06/2020, 2:56 PMAny.Nicholas Bilyk
08/06/2020, 2:59 PMstreetsofboston
08/06/2020, 3:05 PMAny? (fun <T> getFoo(….) …)
or any other upper-bound you want. In the example of getFoo you provided, <T> looks good enough (no need for <T: Any>, it seems),