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() }
如果您想将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() }
- 警告:警告:注释处理器“android.arch.lifecycle.LifecycleProcessor”支持的源版本“RELEASE_7”小于“源”1.8
- kotlin和ArgumentCaptor – IllegalStateException
- 按字符和长度排序字符串
- 处理android kotlin中的click事件:setOnClickListener只有在双击时才起作用
- Kotlin – 从数组中删除重复的字符串的习惯方法?
- 有没有一种干净的方式在Kotlin中使用Groovy的扩展方法?
- kotlin扩展方法访问另一个kt
- Kotlin自动代码调用委托模式
- Kotlin – 错误:无法找到或加载主类_DefaultPackage