Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 981
Morgoth Avatar asked Mar 05 '23 08:03

Morgoth


1 Answers

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?"
like image 151
luminous_arbour Avatar answered Mar 16 '23 01:03

luminous_arbour