如何在Kotlin中将vararg与不同的泛型一起使用? [英] How can I use vararg with different generics in Kotlin?
问题描述
我想对每个参数具有不同类型的泛型使用vararg
I want to use vararg with generics with different types of each arguments
我已经尝试过的方法:
class GeneralSpecification<T> {
fun <P> ifNotNullCreateSpec(vararg propToCreateFun: Pair<P?, (P) -> Specification<T>>): List<Specification<T>> =
propToCreateFun.mapNotNull { (prop, funCreateSpec) ->
prop?.let(funCreateSpec)
}
...
}
但是我不能这样使用:
ifNotNullCreateSpec("asdf" to ::createStringSpec, 5 to ::createIntSpec)
(可变参数对中的不同类型)
(different types in vararg pairs)
当我需要限制vararg中的类型时,如何将vararg与不同的泛型一起使用? (pair.first类型取决于pair.second类型)
How can I use vararg with different generics, when I need to restrict types in vararg? (pair.first type depends on pair.second type)
推荐答案
考虑使用您自己的类型,而不是使用Pair
:
Instead of using Pair
, consider defining your own type:
class WithSpec<P, T>(val prop: P?, val funCreateSpec: (P) -> Specification<T>) {
fun spec() = prop?.let(funCreateSpec)
}
为什么?因为它可以让你做
Why? Because it allows you to do
class GeneralSpecification<T> {
fun ifNotNullCreateSpec(vararg propToCreateFun: WithSpec<*, T>): List<Specification<T>> =
propToCreateFun.mapNotNull { it.spec() }
...
}
ifNotNullCreateSpec(WithSpec("asdf", ::createStringSpec), WithSpec(5, ::createIntSpec))
如果您想更接近原始代码,可以轻松添加类似于to
的扩展函数,并返回WithSpec
.
You can easily add a to
-like extension function returning WithSpec
if you want to get even closer to your original code.
请参见 https://kotlinlang.org/docs/reference/generics. html#star-projections (如果您不知道*
是什么意思).
See https://kotlinlang.org/docs/reference/generics.html#star-projections if you don't know what *
means.
这篇关于如何在Kotlin中将vararg与不同的泛型一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!