英文:
List of generic<T> class instances - call function that takes T
问题
val t = list[0].get()
t.foo = bar
(list[0] as MyClass<BaseClass>).process(t)
英文:
I have a class that looks like this:
class MyClass<T : BaseClass> {
fun get(): T
fun process(thing: T)
}
If I had a single instance of this class of type X
, for example, I could do:
val instance: MyClass<X> = getInstance()
val t = instance.get()
t.foo = bar
instance.process(t)
However, instead of having just one, I have a list of them, each having a different type as T
:
val list: List<MyClass<*>> = getInstances()
val t = list[0].get()
t.foo = bar
// Error here: type mismatch - BaseClass cannot be converted to Nothing
list[0].process(t)
That is because MyClass<*>.get()
returns BaseClass
and, in contrast, MyClass<*>.process()
takes Nothing
as its argument, so it cannot be called.
How can I call process()
on one of the list members, with the result of get()
?
So far, my solution is:
val t = list[0].get()
t.foo = bar
@Suppress("UNCHECKED_CAST")
(list[0] as MyClass<BaseClass>).process(t)
Is there a better way?
答案1
得分: 4
You can simply extract the piece of code where you need the T
into a generic function (which kinda captures the actual generic type of MyClass
for the body of your function):
fun <T> MyClass<T>.getAndProcess(foo: Foo) {
val t = get()
t.foo = foo
process(t)
}
This way of extracting into a generic function basically allows you, like in math, to declare "let T
be the T
of that MyClass
instance".
Then you can call getAndProcess()
on a MyClass<*>
like this:
val list: List<MyClass<*>> = getInstances()
list[0].getAndProcess(foo = bar)
英文:
You can simply extract the piece of code where you need the T
into a generic function (which kinda captures the actual generic type of MyClass
for the body of your function):
fun <T> MyClass<T>.getAndProcess(foo: Foo) {
val t = get()
t.foo = foo
process(t)
}
This way of extracting into a generic function basically allows you, like in math, to declare "let T
be the T
of that MyClass
instance".
Then you can call getAndProcess()
on a MyClass<*>
like this:
val list: List<MyClass<*>> = getInstances()
list[0].getAndProcess(foo = bar)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论