Kotlin方法泛型类型验证

时间:2017-03-24 21:59:58

标签: kotlin

我试图编写一个采用KProperty1和R对象的方法

inline fun <T: Any, R: Any> List<T>.test(prop1: KProperty1<T, R>, prop2: R): List<T>

除了我没有在prop2上进行类型检查。有没有办法确保prop2是R型?

这是一个更完整的例子

class Foo

class Bar(val foo: Foo)

fun main(args: Array<String>): Unit {
    val list = listOf(Bar(Foo()))
    list.test(Bar::foo, Foo()) // This should work
    list.test(Bar::foo, "") // I want this to be a type error since a string is not a Foo
}

inline fun <T: Any, R: Any> List<T>.test(prop1: KProperty1<T, R>, prop2: R): List<T> {
    println(prop1.invoke(this.first())::class == prop2::class)
    return listOf()
}

1 个答案:

答案 0 :(得分:0)

如果您想将R限制为Foo的子项,请提供上限约束:

inline fun <T: Any, R: Foo> List<T>.test(prop1: KProperty1<T, R>, prop2: R): List<T> {
    println(prop1.invoke(this.first())::class == prop2::class)
    return listOf()
}