KClass reference for nullable values

2.6k views Asked by At

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 (ie represente 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.

4

There are 4 answers

0
Antoine On BEST ANSWER

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
4
zsmb13 On

KotlinPoet 0.2.0 has just been released, and added support for nullable types, through asNullable() calls. For example:

PropertySpec.builder("name", TypeName.get(String::class).asNullable()).build()

... will create:

val name: java.lang.String?

Note that as the release notes mention, some function signatures in 0.2.0 have been flipped from the (type, name) order to use (name, type) order instead, so don't be scared when upgrading breaks your code.

1
mfulton26 On

No. Kotlin has Nullable types and Non-Null Types but it does not have a concept of nullable classes and non-null classes. A KType is a classifier plus nullability where a classifier can be a KClass.

KotlinPoet 0.1.0 did not have a way to represent nullable types but support for such was added in 0.2.0 via TypeName.asNullable. e.g.:

val type = TypeName.get(String::class).asNullable()
1
Matej On

As for KotlinPoet 1.1.0:

Any::class.asTypeName().copy(nullable = true)

https://github.com/square/kotlinpoet#nullable-types