Hi guys! Does anyone know if there is a better way...
# announcements
z
Hi guys! Does anyone know if there is a better way to do this so that I don't have to do explicitly casting?
Copy code
fun <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)
    }
}
s
You’ll need the explicit casting to
Foo<T>
, but you can do it only once instead of within each when-branch:
Copy code
return when (defaultValue) { 
    ...
} as Foot<T>
👍 1
z
Ah true, nice 🙂 thanks
n
When you call getFoo is the type of defaultValue known or is it Any? If you know the type at the call site you could just overload:
Copy code
fun 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)
s
It has the erased type of its upper-bound, in your example that would be
Any
.
n
In the example, yes, but I was confirming if it needed to be Any.
s
It depends on your business-case/logic….. 🙂 It could be just
Any?
(
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),