pkl icon indicating copy to clipboard operation
pkl copied to clipboard

Missing union type support for Kotlin codegen

Open madisp opened this issue 1 year ago • 7 comments
trafficstars

Execution failed for task ':pkl-playground:genKotlin'.
> Pkl union types are not supported by the Kotlin code generator.

Bit of a tall ask, I know, but it'd be wonderful if we could map union types into some form of Kotlin structure.

madisp avatar Feb 03 '24 22:02 madisp

It'd be great to support this, but it's not clear how they should turn into Kotlin. Feel free to provide suggestions, though.

bioball avatar Feb 04 '24 00:02 bioball

For now this will have to be implemented with sealed class https://kotlinlang.org/docs/sealed-classes.html

jamesward avatar Feb 04 '24 05:02 jamesward

yup, most likely. sealed class needs a name though, maybe take a similar approach to string union to enum mapping that all union types should be defined via a type alias?

E.g. this wouldn't still map to Kotlin:

class Foo {
  items: Listing<Bar | Baz>
}

but this would?

typealias FooItem = Bar | Baz

class Foo {
  items: Listing<FooItem>
}

madisp avatar Feb 04 '24 11:02 madisp

Hi all, I'm evaluating pkl as a configuration language for an API GW. My server is in Kotlin and not having union mapped to Kotlin (or Java) is a show stopper. There any thoughts about adding them? or what would be a workaround for something with the same semantic but supported by Kotlin? My scenario is something like typealias HttpMethod = "GET" | "POST" | "PUT" | "DELETE" Thanks

giordano-newday avatar Jul 01 '24 17:07 giordano-newday

@giordano-newday: We don't have a great way to model most union types as Kotlin, because it's missing anonymous sum types. However, typealiases of string literal unions are a special case, and are no problem to represent.

This pkl:

typealias HttpMethod = "GET" | "POST" | "PUT" | "DELETE"

Turns into the following Kotlin:

  enum class HttpMethod(
    val value: String
  ) {
    GET("GET"),

    POST("POST"),

    PUT("PUT"),

    DELETE("DELETE");

    override fun toString() = value
  }

bioball avatar Jul 01 '24 17:07 bioball

I think it would for my scenarios. Thanks @bioball.

giordano-newday avatar Jul 01 '24 18:07 giordano-newday