【发布时间】:2020-10-03 13:37:27
【问题描述】:
我有一个来自Union type Scala 的联合类型 Int 和 String,我想将它添加到通用方法中。你能帮我写这个方法,没有编译错误。
object OrTypeMain extends App {
class StringOrInt[T]
object StringOrInt {
implicit object IntWitness extends StringOrInt[Int]
implicit object StringWitness extends StringOrInt[String]
}
object Bar {
def foo[T: StringOrInt](x: T): Unit = x match {
case _: String => println("str")
case _: Int => println("int")
}
// target method
def reverse[T: StringOrInt](x: T): StringOrInt = x match { // not compile
def reverse[T: StringOrInt](x: T): T = x match { // not compile too
case x: String => x + "new"
case y: Int => y + 5
}
}
Bar.reverse(123)
Bar.reverse("sad")
}
【问题讨论】:
标签: scala pattern-matching typeclass implicit union-types