Kotlin方法泛型类型验证

Kotlin方法泛型类型验证,kotlin,Kotlin,我正在尝试编写一个方法,该方法采用KProperty1和R对象,如下所示 inline fun <T: Any, R: Any> List<T>.test(prop1: KProperty1<T, R>, prop2: R): List<T> inlinefunlist.test(prop1:KProperty1,prop2:R):列表 除了我没有在prop2上进行类型检查。有没有办法确保prop2是R型的 下面是一个更完整的示例 class

我正在尝试编写一个方法,该方法采用KProperty1和R对象,如下所示

inline fun <T: Any, R: Any> List<T>.test(prop1: KProperty1<T, R>, prop2: R): List<T>
inlinefunlist.test(prop1:KProperty1,prop2:R):列表
除了我没有在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()
}
class-Foo
类栏(val-foo:foo)
趣味主线(参数:数组):单位{
val list=listOf(Bar(Foo()))
test(Bar::foo,foo())//这应该行得通
test(Bar::foo,“”//我希望这是一个类型错误,因为字符串不是foo
}
内联乐趣列表。测试(prop1:KProperty1,prop2:R):列表{
println(prop1.invoke(this.first())::class==prop2::class)
返回列表()
}

如果要将
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()
}
inlinefunlist.test(prop1:KProperty1,prop2:R):列表{
println(prop1.invoke(this.first())::class==prop2::class)
返回列表()
}

请提供更多详细信息。不能将非R类型的对象作为prop2参数传递。