返回联合类型的通用方法

问题描述 投票:0回答:1

我有一个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
1个回答
1
投票

为什么reverse无法编译在这里说明:

Why can't I return a concrete subtype of A if a generic subtype of A is declared as return parameter?

Type mismatch on abstract type used in pattern matching

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

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)
© www.soinside.com 2019 - 2024. All rights reserved.