Scala是否具有F#的“类型”?

时间:2017-02-21 11:03:10

标签: scala f#

F#中的类型声明示例:

type ActiveCartData = { UnpaidItems: string list }
type PaidCartData = { PaidItems: string list; Payment: float }

type ShoppingCart = 
    | EmptyCart  // no data
    | ActiveCart of ActiveCartData
    | PaidCart of PaidCartData

我们如何使用traitcase class和/或case object在Scala中执行类似操作?

一个开始:

trait ShoppingCart
case object EmptyCart extends ShoppingCart
case object ActiveCart extends ShoppingCart
case object PaidCart extends ShoppingCart

但是如何与数据持有者类型建立关系?

1 个答案:

答案 0 :(得分:7)

如果我理解正确,您正在寻找case classes而不是case objects。他们可以包装数据:

sealed trait ShoppingCart
case object EmptyCart extends ShoppingCart
case class ActiveCart(unpaidItems: Seq[String]) extends ShoppingCart
case class PaidCart(paidItems: Seq[String], payment: Float) extends ShoppingCart

或(如果你想保留这些持有者数据类型,除非它们非常复杂,否则我可能不会这样做)

sealed trait ShoppingCart
case object EmptyCart extends ShoppingCart
case class ActiveCart(unpaidItems: ActiveCartData) extends ShoppingCart
case class PaidCart(paidItems: PaidCartData) extends ShoppingCart