科特林和歧视工会(总和类型) [英] Kotlin and discriminated unions (sum types)

查看:91
本文介绍了科特林和歧视工会(总和类型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

科特林是否有歧视工会(和式)之类的东西?此(F#)的惯用科特林译本是什么:

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

type OrderMessage =
    | New of Id: int * Quantity: int
    | Cancel of Id: int

let handleMessage msg = 
    match msg with
        | New(id, qty) -> handleNew id qty
        | Cancel(id) -> handleCxl id

推荐答案

在OO语言(例如Kotlin或Scala)中实现这种抽象的常见方法是通过继承:

The common way of implementing this kind of abstraction in an OO-language (e.g. Kotlin or Scala) would be to through inheritance:

open class OrderMessage private () { // private constructor to prevent creating more subclasses outside
    class New(val id: Int, val quantity: Int) : OrderMessage()
    class Cancel(val id: Int) : OrderMessage()
}

如果愿意,可以将公共部分推入超类:

You can push the common part to the superclass, if you like:

open class OrderMessage private (val id: Int) { // private constructor to prevent creating more subclasses outside
    class New(id: Int, val quantity: Int) : OrderMessage(id)
    class Cancel(id: Int) : OrderMessage(id)
}

类型检查器不知道这样的层次结构是关闭的,因此当您对它进行类似大小写的匹配(when -expression)时,它会抱怨说它并不详尽,但这将得到解决.很快.

The type checker doesn't know that such a hierarchy is closed, so when you do a case-like match (when-expression) on it, it will complain that it is not exhaustive, but this will be fixed soon.

更新:尽管Kotlin不支持模式匹配,但是您可以使用 when 表达式作为智能强制类型转换来获得几乎相同的行为:

Update: while Kotlin does not support pattern matching, you can use when-expressions as smart casts to get almost the same behavior:

when (message) {
  is New -> println("new $id: $quantity")
  is Cancel -> println("cancel $id")
}

此处中了解更多信息.

这篇关于科特林和歧视工会(总和类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆