6

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.

Morgoth
  • 4,935
  • 8
  • 40
  • 66
  • A `String?` isn't a class of its own and doesn't have a class object. `String?::class` could be the class object of `String` or the class object of `null` (which doesn't make sense). This would be ambiguous. – Michael Butscher Sep 25 '18 at 01:08

1 Answers1

8

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?"
Raphael
  • 9,779
  • 5
  • 63
  • 94
luminous_arbour
  • 106
  • 1
  • 4