你看到的原因
Error: "Type mismatch. Required: String, found: T"
是不是默认Scala 2在Predef中定义了如下隐式方法
implicit final class any2stringadd[A](private val self: A) extends AnyVal {
def +(other: String): String = String.valueOf(self) + other
}
(这不会在 Scala 3 中编译)。如果您想编写适用于所有整数类型的单个非泛型计算器类(无论这对您意味着什么 - Scala 没有将类型限制为 Int、Byte、Long 的继承层次结构) .您将使用自己的 Integer 类型类
class Calculator {
def add[A: Integer](lhs: A, rhs: A): A = implicitly[Integer[A]].plus(lhs, rhs)
}
有以下定义
trait Integer[A] {
def plus(lhs: A, rhs: A): A
}
object Integer {
implicit val Int: Integer[Int] = new Integer[Int] {
override def plus(lhs: Int, rhs: Int): Int = lhs + rhs
}
// note explicit toByte cast -> byte addition can overflow!
// (thus result type is Int and you might want to stick
// to the original type in your use case)
implicit val Byte: Integer[Byte] = new Integer[Byte] {
override def plus(lhs: Byte, rhs: Byte): Byte = (lhs + rhs).toByte
}
}
为了让它看起来更好一点,您可以利用扩展方法。
class Calculator {
import Integer._
def add[A: Integer](lhs: A, rhs: A): A = lhs + rhs
}
object Integer {
implicit class IntegerOps[A: Integer](lhs: A) {
def +(rhs: A): A = implicitly[Integer[A]].plus(lhs, rhs)
}
// the rest of the object stays the same
}
使用 Scala 3,您可以更简洁地编写它
class Calculator {
def add[A: Integer](lhs: A, rhs: A): A = lhs + rhs
}
trait Integer[A]:
extension(a: A) def +(b: A): A
given Integer[Int] with
extension(a: Int) def +(b: Int): Int = a + b
given Integer[Byte] with
extension(a: Byte) def +(b: Byte): Byte = (a + b).toByte
编辑:根据@Tim 的建议,您可以使用预定义的Integral 类型类。如果您想自己实现类似的类型类,我仍然会留下我的答案作为参考。