returns 联合类型的通用方法

General-purpose method that returns a union type

我有一个来自 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")
}

为什么 reverse 不编译在这里解释:

用编译时类型替换运行时模式匹配class。 StringOrInt 已经是类型 class。只需将您的操作移到那里即可。

trait StringOrInt[T] {
  def reverse(t: T): T
}    
object StringOrInt {
  implicit object IntWitness extends StringOrInt[Int] {
    override def reverse(t: Int): Int = t + 5
  }

  implicit object StringWitness extends StringOrInt[String] {
    override def reverse(t: String): String = t + "new"
  }  
}

def reverse[T: StringOrInt](x: T): T = implicitly[StringOrInt[T]].reverse(x)