Kotlin and discriminated unions (sum types)

后端 未结 3 1125
慢半拍i
慢半拍i 2021-02-03 17:36

Does Kotlin have anything like discriminated unions (sum types)? What would be the idiomatic Kotlin translation of this (F#):

type OrderMessage =
    | New of Id         


        
3条回答
  •  清歌不尽
    2021-02-03 17:59

    Kotlin's sealed class approach to that problem is extremely similar to the Scala sealed class and sealed trait.

    Example (taken from the linked Kotlin article):

    sealed class Expr {
        class Const(val number: Double) : Expr()
        class Sum(val e1: Expr, val e2: Expr) : Expr()
        object NotANumber : Expr()
    }
    

提交回复
热议问题