我试图匹配可空类型 String?
在 Kotlin 反射(reflection)练习中:
data class Test(a: String, b: String?)
val test = Test("1", "2")
val properties = test::class.declaredMemberProperties
val propertyNames = properties.joinToString(",") {
when (it.returnType) {
String?::class.createType() -> "string?"
String::class.createType() -> "string"
else -> throw Exception()
}
}
唉,它因错误而失败,
Type in a class literal must not be nullable
, 为 String?::class
.
最佳答案
createType
函数有一个可选的可为空的参数,当我测试它时似乎可以工作。
import kotlin.reflect.full.*
String::class.createType(nullable = true) -> "string?"
关于reflection - 获取可空类型的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52489204/