4

我正在尝试匹配String?Kotlin 反射练习中可为空的类型:

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, for String?::class

4

1 回答 1

7

createType函数有一个可选的可空参数,当我测试它时似乎可以工作。

import kotlin.reflect.full.*

String::class.createType(nullable = true) -> "string?"
于 2018-09-25T03:02:39.713 回答