kotlinpoet icon indicating copy to clipboard operation
kotlinpoet copied to clipboard

Support definitely non-nullable types

Open ZacSweers opened this issue 2 years ago • 6 comments

From https://kotlinlang.org/docs/whatsnew17.html#stable-definitely-non-nullable-types

Open to suggestions on the API for this, went back and forth on an explicit asDefinitelyNonNullable() or copy(isDefinitelyNonNullable: Boolean) overload. Also open to suggestions on whether or not any of the checks are cases we should silently "fix" for them, like setting isDefinitelyNonNullable to false if copying over as nullable.

ZacSweers avatar Jun 17 '22 01:06 ZacSweers

That sounds reasonable to me. API like this maybe?

TypeVariableName(..., intersects = listOf(ANY))

The thing I'm less sure about though is how to indicate that this needs to be emitted.

ZacSweers avatar Jun 17 '22 03:06 ZacSweers

I was thinking more like IntersectionTypeName(TypeVariableName("T"), ANY)

JakeWharton avatar Jun 17 '22 13:06 JakeWharton

Hmmm, is that a breaking change if TypeName is currently sealed to add another?

ZacSweers avatar Jun 17 '22 14:06 ZacSweers

It's source incompatible and will cause a runtime exception for when's without an else.

JakeWharton avatar Jun 20 '22 19:06 JakeWharton

What if we made isDefinitelyNonNullable private and introduced IntersectionTypeName as a function that returns TypeVariableName with isDefinitelyNonNullable set to true? While IntersectionTypeName will support any type as the second argument, we can make it fail at runtime and say that only ANY is currently supported. When intersection types become more common in Kotlin we may be close enough to KotlinPoet 2.0, at which point we can promote IntersectionTypeName to an actual subtype of TypeName.

Egorand avatar Jun 27 '22 17:06 Egorand

I think that seems reasonable. In general for 2.0, I think we should take a closer look at how kotlinc models these and consider mirroring it, including making TypeName no longer sealed. There's a few things that don't quite fit the kotlin model that are leftovers from JavaPoet. I'll add them to the 2.0 ideas issue

ZacSweers avatar Jun 28 '22 18:06 ZacSweers