Morgoth
Morgoth

Reputation: 5184

Get the class of nullable type

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.

Upvotes: 7

Views: 2312

Answers (1)

luminous_arbour
luminous_arbour

Reputation: 126

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?"

Upvotes: 10

Related Questions