Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Kotlin API for anonymous structs #88

Open
snowsignal opened this issue Apr 3, 2023 · 0 comments
Open

Improve Kotlin API for anonymous structs #88

snowsignal opened this issue Apr 3, 2023 · 0 comments
Labels
feature-request A request for a new feature

Comments

@snowsignal
Copy link
Contributor

Take the following code snippet:

#[typeshare]
#[serde(tag = "type", content = "content")]
pub enum Menu {
    Breadsticks {
        marinara: bool
    },
    Pizza {
        pepperoni: bool,
        anchovies: bool
    },
}

This will generate the following output:

@Serializable
data class MenuBreadsticksInner (
  val marinara: Boolean
)

@Serializable
data class MenuPizzaInner (
  val pepperoni: Boolean
  val anchovies: Boolean
)

@Serializable
sealed class Menu {
  @Serializable
  @SerialName("Breadsticks")
  data class Breadsticks(val content: MenuBreadsticksInner): Menu()
  @Serializable
  @SerialName("Pizza")
  data class Pizza(val content: MenuPizzaInner): Menu()
}

However, this approach means we have to use .content to access a field.

Ideally, the Kotlin output should look more like this to be more ergonomic:

sealed interface Menu {
    interface Breadsticks : Menu {
        val marinara: Boolean
    }
    interface Pizza: Menu {
        val pepperoni: Boolean
        val anchovies: Boolean
    }
}

This would let us do:

fun main() {
   val test: Menu = object : Menu.Breadsticks {
       override val marinara: Boolean = true
   }
   
   when (test) {
       is Menu.Breadsticks -> println(test.marinara)
       is Menu.Pizza -> println(test.pepperoni)
   }
}
@snowsignal snowsignal added the feature-request A request for a new feature label Apr 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature-request A request for a new feature
Projects
None yet
Development

No branches or pull requests

1 participant