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