【发布时间】:2017-10-23 16:05:04
【问题描述】:
我希望能够彻底匹配密封特征实现的类型,如下例所示。理想情况下,我想尽可能避免使用反射(TypeTags)和隐式转换。有什么方法可以穷举匹配密封特征的类型?
object DataTypes {
sealed trait StrFy {
def stringify: String
}
final case class StrFyString(s: String) extends StrFy {
def stringify = s
}
final case class StrFyInt(i: Int) extends StrFy {
def stringify = i.toString
}
def stringifyThings[T <: StrFy](values: T*): String = {
val label = T match {
case StrFyString => "string"
case StrFyInt => "integer"
// cases that don't extend StrFy cause a compile error
}
"The " + label + " values are: " + values.map(_.stringify.fold("")(_+", "+_))
}
def printStringified(): Unit = {
println(stringifyThings(StrFyString("foo"), StrFyString("bar"))) // should print: "the string values are: foo, bar"
println(stringifyThings(StrFyInt(1), StrFyInt(2), StrFyInt(3))) // should print: "the integer values are: 1, 2, 3"
}
}
【问题讨论】:
-
stringifyThings(StrFyString("s"), StrFyInt(9))应该得到什么? -
jwvh: 它应该给出一个错误(stringifyThings 必须采用同构列表)
标签: scala