Coproduct 优于 `sealed trait` 的好处?
Benefit of Coproduct over `sealed trait`?
我阅读了以下关于 coproducts in the excellent Shapeless Guide 的内容:
... it’s worth stating that Coproducts aren’t particularly special. The functionality above can be achieved using Either and Nothing in place of :+:
and CNil.
这是上面的代码:
import shapeless.{Coproduct, :+:, CNil, Inl, Inr}
case class Red()
case class Amber()
case class Green()
type Light = Red :+: Amber :+: Green :+: CNil
val red: Light = Inl(Red())
// red: Light = Inl(Red())
val green: Light = Inr(Inr(Inl(Green())))
// green: Light = Inr(Inr(Inl(Green())))
根据我自己的理解,使用余积比 sealed trait
有什么好处(如果有的话)?
与使用 HList
而不是 case class
的好处相同:您可以编写适用于所有联积或满足某些条件的所有联积的通用代码。然后使用 Generic
使相同的代码也适用于 sealed trait
s。
一个好处类似于使用类型 类 而不是继承:ad-hoc 多态性。您可以使用任何类型制作联积,甚至是您无法控制的类型,例如字符串和整数。你不能用密封的特征来做到这一点(除非你用笨拙的 StringHolder
和 IntHolder
大小写 类 来包装它们)。
我阅读了以下关于 coproducts in the excellent Shapeless Guide 的内容:
... it’s worth stating that Coproducts aren’t particularly special. The functionality above can be achieved using Either and Nothing in place of :+: and CNil.
这是上面的代码:
import shapeless.{Coproduct, :+:, CNil, Inl, Inr}
case class Red()
case class Amber()
case class Green()
type Light = Red :+: Amber :+: Green :+: CNil
val red: Light = Inl(Red())
// red: Light = Inl(Red())
val green: Light = Inr(Inr(Inl(Green())))
// green: Light = Inr(Inr(Inl(Green())))
根据我自己的理解,使用余积比 sealed trait
有什么好处(如果有的话)?
与使用 HList
而不是 case class
的好处相同:您可以编写适用于所有联积或满足某些条件的所有联积的通用代码。然后使用 Generic
使相同的代码也适用于 sealed trait
s。
一个好处类似于使用类型 类 而不是继承:ad-hoc 多态性。您可以使用任何类型制作联积,甚至是您无法控制的类型,例如字符串和整数。你不能用密封的特征来做到这一点(除非你用笨拙的 StringHolder
和 IntHolder
大小写 类 来包装它们)。