0
我想写需要KProperty1和像这样科特林方法泛型类型验证
inline fun <T: Any, R: Any> List<T>.test(prop1: KProperty1<T, R>, prop2: R): List<T>
除了我没有收到关于PROP2类型检查R的对象的方法。有什么办法可以确保prop2是R型的?
这里是如果你想限制R
到Foo
儿童则提供上限约束更完整的示例
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()
}
提供更多的细节请。你不能传递不是R类型的对象作为prop2参数。 – Ufkoku