Get the class of nullable type

2.1k Views Asked by At

I am trying to match the type of the nullable String? in a Kotlin reflection exercise:

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()
        }
}

Alas, it is failing with the error, Type in a class literal must not be nullable, for String?::class.

1

There are 1 best solutions below

1
On BEST ANSWER

The createType function has an optional nullable parameter that seemed to work when I tested it.

import kotlin.reflect.full.*

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