Kotlin实体类型参数不会智能投射 [英] Kotlin reified type parameter doesn't smart cast
问题描述
我正在尝试设置未初始化的值,并试图让下面的工作。这主要是对泛化泛型的强大(和限制)的好奇。
我试图为数据类的可选参数提供默认值。 b
$ b
inline fun< reified T> uninitialized():T = when(T :: class){
Long :: class - > -1L //类型不匹配。要求:T找到:长
String :: class - > // 类型不匹配。 Required:T Found:String
//等等...
else - >抛出UnsupportedOperationException(没有为+ T :: class定义未初始化的值)
数据类Thing(
var id:Long =未初始化的(),
var name:String = uninitialized()//等等...
)
当包含
时,是类型
子句时,Kotlin具有智能铸造。在这个例子中,智能铸造不会踢,所以这不会编译。
任何想法可以完成类似的事情?
但是,您可以将手动演员应用到 T
,这将按预期工作。下面是你的示例函数的一个工作版本,已更新,以处理Kotlin的反射库的特性,该库将在1.1中修复:
inline有趣的东西T:任何> uninitialized():T = when(T :: class.java){
Long :: class.javaPrimitiveType,Long :: class.javaObjectType - > -1L as T
String :: class.java - > as T
//等等...
else - >抛出UnsupportedOperationException(没有为+ T :: class定义未初始化的值)
数据类Thing(
var id:Long =未初始化的(),
var name:String = uninitialized()//等等...
)
fun main(args:Array< String>){
val t = Thing()
println(t.id)
}
I was experimenting with setting uninitialized values and was trying to get the following to work. This is mostly a curiosity in the power (and limitations) of reified generics.
I was attempting to provide default values for optional parameters of data classes.
inline fun <reified T> uninitialized(): T = when (T::class) {
Long::class -> -1L // Type mismatch. Required: T Found: Long
String::class -> "" // Type mismatch. Required: T Found: String
// and so on...
else -> throw UnsupportedOperationException("No uninitialized value defined for " + T::class)
}
data class Thing(
var id: Long = uninitialized(),
var name: String = uninitialized() // and so on...
)
When when
includes is Type
clauses, Kotlin has smart casting. In this example, smart casting isn't kicking in so this will not compile.
Any ideas to accomplish something similar?
A smart cast is applied to a specific object after you use is
to check its type or compare it with null
. In your example, there is no specific object for which you check the type, and nothing to apply the smart cast to.
However, you can apply manual casts to T
, which will work as expected. Here's a working version of your sample function, updated to handle the peculiarities of Kotlin's reflection library which will be fixed in 1.1:
inline fun <reified T : Any> uninitialized(): T = when (T::class.java) {
Long::class.javaPrimitiveType, Long::class.javaObjectType -> -1L as T
String::class.java -> "" as T
// and so on...
else -> throw UnsupportedOperationException("No uninitialized value defined for " + T::class)
}
data class Thing(
var id: Long = uninitialized(),
var name: String = uninitialized() // and so on...
)
fun main(args: Array<String>) {
val t = Thing()
println(t.id)
}
这篇关于Kotlin实体类型参数不会智能投射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!