首页 > 解决方案 > 获取可为空类型的类

问题描述

我正在尝试匹配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

标签: reflectionkotlinkotlin-reflect

解决方案


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

import kotlin.reflect.full.*

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

推荐阅读