Inferring/casting 泛型到具体类型

Inferring/casting generic type to concrete type

当我尝试编译时:

package com

object typeparam extends App {

  new MyClass[Int]().f2(3)

  class MyClass[B] {

    def f2(b: B): B = {
      b + b
    }

  }

}

我收到编译器错误

type mismatch;
[error]  found   : B
[error]  required: String
[error]       b + b
[error]           ^
[error] one error found

为什么 b 没有被推断为 Int,因为当我调用 class 我使用类型参数 Int 时?

如果我改为使用:

package com

object typeparam extends App {

  println(new MyClass[Int]().f2(3) * 3)

  class MyClass[B] {

    def f2(b: B): B = {
      b
    }

  }

}

正确打印了值 9。所以似乎正确推断了 Int 类型。

这与类型擦除有关吗?

它与类型擦除没有任何关系。您的类型参数 B 是无界的,并非每个类型都有 + 方法。但是每个类型都可以隐式转换为 String 以便使用 + 方法(推断为 Any),这正是这里发生的事情。

如果您希望它仅适用于数字,也许需要 Numeric 特性?

class MyClass[B](implicit num: Numeric[B]) {
   def f2(b: B): B = num.plus(b, b)
}

scala> def myInst = new MyClass[Int]
myInst: MyClass[Int]

scala> myInst.f2(3)
res0: Int = 6