Kotlin方法通用typesvalidation

我试图写一个方法,采取KProperty1和R的对象像这样

inline fun  List.test(prop1: KProperty1, prop2: R): List 

除非我没有对prop2进行types检查。 有什么办法可以确保prop2是R型的吗?

这是一个更完整的例子

 class Foo class Bar(val foo: Foo) fun main(args: Array): 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  List.test(prop1: KProperty1, prop2: R): List { println(prop1.invoke(this.first())::class == prop2::class) return listOf() } 

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

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