获取可空类型的 class

Get the class of nullable type

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

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 函数有一个可选的可为 null 的参数,我测试它时似乎可以使用。

import kotlin.reflect.full.*

String::class.createType(nullable = true) -> "string?"