kotlinkotlinpoet

KClass reference for nullable values


In Kotlin, when declaring getting a KClass for a type, such as String::class (which represents values whose type will be String), is there a syntax to indicate that the value is nullable (i.e. represent String? values instead of String).

The context is that I'm trying to generate Kotlin classes using KotlinPoet but all properties I create (with PropertySpec.builder) are not nullable (String for instance, when what I actually want is String?).

Thanks for your help.


Solution

  • In case someone needs this : As of KotlinPoet 0.3.0, the syntax is :

    PropertySpec.builder("myVar", String::class.asTypeName().asNullable()).mutable(true).initializer("%S", null)
    

    to produce :

    var myVar:String? = null