Kotlin-native: [Feature Request] Add typed ordinal for enums bridged to Obj-C?

Created on 9 Jan 2019  路  7Comments  路  Source: JetBrains/kotlin-native

Enums bridged to Obj-C are subclasses of <prefix>KotlinEnum, which has an ordinal property with this signature:

@property (readonly) int32_t ordinal;

It would be nice if subclasses had a typedOrdinal property (or something similar) that was typed using a generated NS_ENUM. Here's an example of what I'm proposing:

Kotlin

enum class Weekend { SATURDAY, SUNDAY }

Obj-C property in MyLibKotlinEnum subclass

@property (readonly) MyLibWeekend typedOrdinal;

Related Generated Obj-C Enum Type

typedef NS_ENUM(int32_t, MyLibWeekend) {
    MyLibWeekendSaturday,
    MyLibWeekendSunday
};

This would improve usability of these in Swift/Obj-C a lot because the compiler would then be able to give warnings/errors about switch statements not being exhaustive.

There may be other ways of getting this to happen, but hopefully my direction/goal here is well-communicated.

Most helpful comment

Gotcha. Exhaustive whens for enums with associated values is a really nice feature, and asking Swift devs to not be able to leverage this when they consume Kotlin native will turn off iOS devs and hurt overall Kotlin multiplatform adoption

All 7 comments

This makes sense, thank you for the idea.
Btw, it seems to be possible to reuse ordinal property in subclass but make it typed, i.e.

@property (readonly) int32_t ordinal;

(in MyLibKotlinEnum)

@property (readonly) MyLibWeekendOrdinal ordinal;

(in subclass).

Ah yes that might be possible! Thanks!

Would this proposal allow Swift to consume Kotlin sealed classes in the Swift equivalent of Kotlin's exhaustive when?

No sorry. This is just to allow switching on basic enums, similar to Obj-C enums.

Gotcha. Exhaustive whens for enums with associated values is a really nice feature, and asking Swift devs to not be able to leverage this when they consume Kotlin native will turn off iOS devs and hurt overall Kotlin multiplatform adoption

It'd also be nice if something could be done for Sealed classes. This might not be able to be done via ObjC - but sealed classes can be represented as Swift enums, which is probably a larger problem to solve.

but sealed classes can be represented as Swift enums,

This is actually not entirely correct. Kotlin sealed classes and Swift enums are quite different concepts. For example:

  • Swift enum cases don't define new types, while Kotlin sealed classes do.
  • There are no such thing as "sub-cases" in Swift enums, while Kotlin sealed classes can have deep hierarchy.
Was this page helpful?
0 / 5 - 0 ratings