I'm struggling with generics here. sorry for how c...
# getting-started
y
I'm struggling with generics here. sorry for how contrived this is, but
Copy code
sealed class Foo {  
    class A(): Foo()  
    class B(): Foo()
    class C(): Foo()
}

class Bar<F: Foo>(val f: F) { }

inline fun <F : Foo,  reified RET : Bar<F>> doSomething(): List<RET> { //... }
now this is fine and I can call it with
doSomething<F, Bar<F>>()
, or I can make the function signature
inline fun <reified RET : Bar<Foo>> doSomething(): List<RET>
, and then call it with
doSomething<Bar<F>>
. but what I'd really like to do is call it with
doSomething<F>()
. is this possible?
a
are you sure you need to define
RET
as a type parameter? It seems like since
Bar
is not open or abstract, you can just use
Bar
Copy code
inline fun <F : Foo> doSomething(): List<Bar<F>> { TODO() }
y
unless I'm missing something, I do - at some point in
doSomething()
, I have to do
someVar is RET
. which makes Kotlin complain that I'm checking for an instance of an erased type.
a
well, now that I think about it, perhaps
Bar
doesn’t need to be generic? Foo is always constrained to A, B, or C, so making Bar generic actually makes the typing less strict
Copy code
class Bar(val f: Foo) { }

inline fun <F : Foo> doSomething(): List<Bar> { //... }
y
I'll give it a try. unfortunately, the class definitions are mostly not my code. otherwise I guess calling it with
doSomething<Bar<F>>()
is really not that bad.