【问题标题】:How to construct simple sum types in Scala?如何在 Scala 中构造简单的求和类型?
【发布时间】:2018-09-27 16:37:14
【问题描述】:

当您在 Scala 中搜索 sum 类型时,您会得到类似的结果:

sealed trait Pet
case class Cat(name: String) extends Pet
case class Fish(name: String, color: Color) extends Pet
case class Squid(name: String, age: Int) extends Pet

是否也可以从Int 或String 等简单数据类型构造求和类型? 类似type simpleType = Int | String | Boolean。

更新:

Scala 3.* 附带此功能,称为 Union Types https://dotty.epfl.ch/docs/reference/new-types/union-types.html。

【问题讨论】:

标签: scala types


【解决方案1】:

查看支持此类析取的https://github.com/frees-io/iota。它需要 Cats 或 Scalaz 作为依赖,并允许创建如下类型:

type Foo = Cop[Int :: String :: Double :: TNil]

【讨论】:

    【解决方案2】:

    你可以使用VALUE CLASSES AND UNIVERSAL TRAITS做类似的事情

    例如:

    sealed trait Numbers extends Any
    case class IntT(val underlying: Int) extends AnyVal with Numbers
    case class LongT(val underlying: Long) extends AnyVal with Numbers
    

    【讨论】:

    • 这听起来很有趣。我会在我的用例中尝试一下,看看效果如何。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2013-08-20
    相关资源
    最近更新 更多