7

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.

Egor
  • 39,695
  • 10
  • 113
  • 130
Antoine
  • 1,068
  • 10
  • 17

4 Answers4

9

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()
mfulton26
  • 29,956
  • 6
  • 64
  • 88
  • Seems like this was removed, it's not available in KotlinPoet `1.12.0`. Arguably, Matej's answer is the replacement. – Marv Oct 17 '22 at 10:56
6

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
Antoine
  • 1,068
  • 10
  • 17
3

As for KotlinPoet 1.1.0:

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

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

Matej
  • 7,728
  • 4
  • 23
  • 30
2

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.

zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • Answer from mfulton26 gives relevant information. I selected this one as it gives the actual code that solves my issue with KotlinPoet (after upgrading to 0.2.0). Thanks to both of you for the detailed answers. – Antoine May 22 '17 at 09:52
  • TypeName.get(String::class) doesn't work anymore in 0.3.0. I can seem to be able to make it work with the new TypeName class. If anyone knows what the correct syntax is now, please let me know ! – Antoine Jun 21 '17 at 08:33
  • Hey, I think what you're supposed to use now is `String::class.asTypeName().asNullable()`. You will need an import for this that IntelliJ doesn't seem to find on its own though: `import com.squareup.kotlinpoet.TypeName.Companion.asTypeName` – zsmb13 Jun 21 '17 at 17:45
  • Yes, I was confused because of the IntelliJ bug that produced an error when I tried to use asTypeName(). Works fine with the import indeed. – Antoine Jun 22 '17 at 07:36