在 Kotlin 中有一种有限形式的具体化泛型。有没有办法使用具体化来过滤泛型类型而不使用getClass()
或as
或任何奇怪的注释,即。仅仅通过使用is
关键字?例如,我有以下结构:
import java.util.*
internal class Layout<out T : LayoutProtocol>(val t: T) {
fun getName(): String {
return t.getName()
}
}
interface LayoutProtocol {
fun getName(): String
}
internal class Vertical : LayoutProtocol {
override fun getName(): String {
return "Vertical"
}
}
internal class Horizontal : LayoutProtocol {
override fun getName(): String {
return "Horizontal"
}
}
fun main(args: Array<String>) {
val layouts = LinkedList<Layout<*>>()
layouts.add(Layout<Horizontal>(Horizontal()))
layouts.add(Layout<Vertical>(Vertical()))
println("Horizontal layouts:")
layouts.filterIsInstance<Layout<Horizontal>>().forEach { println(it.getName()) }
}
这输出:
Horizontal layouts:
Horizontal
Vertical
我希望它输出以下内容。有没有办法获得:
Horizontal layouts:
Horizontal
如果我们查看 的源代码filterIsInstance(...)
,Kotlin 做了一些棘手的事情来规避类型擦除,但仍然不起作用:
/**
* Returns a list containing all elements that are instances of specified type parameter R.
*/
public inline fun <reified R> Iterable<*>.filterIsInstance(): List<@kotlin.internal.NoInfer R> {
return filterIsInstanceTo(ArrayList<R>())
}
/**
* Appends all elements that are instances of specified type parameter R to the given [destination].
*/
public inline fun <reified R, C : MutableCollection<in R>> Iterable<*>.filterIsInstanceTo(destination: C): C {
for (element in this) if (element is R) destination.add(element)
return destination
}
如果这在 Kotlin 中是不可能的,是否有任何语言(JVM 或非 JVM)可以让我执行以下操作:
inline fun <reified R: LayoutProtocol> filterVerticals(from: Iterable<Layout<R>>): Iterable<Layout<Vertical>> {
val dest = ArrayList<Layout<Vertical>>()
for (element in from)
if (element is Layout<Vertical>)
dest.add(element)
return dest
}