我应该创建具有 2 个不同实现的类 Example[T]
:
- 如果
T
可以转换为Numeric
- 另一个案例
我尝试通过隐式转换来做到这一点
class ExampleImplicits{
implicit def convert[T](example: Example[T]): ExampleSecond[T] = new ExampleSecond[T]()
}
class Example[T:Numeric]...
class ExampleSecond[T]...
我认为如果编译器在 scala.Numeric.Implicit 中找不到 T 的隐式转换,那么他就会引发我的隐式转换。
但是当我测试代码时,它的工作原理不是这样的。我怎样才能完成这个特化?
更新
我想要得到什么:
val x = new Example[Int]()
x.methodThatHaveOnlyNumerics()
x.methodThatHaveAllImplementations()
val y = new Example[String]()
y.methodThatHaveAllImplementations()
现在我无法编译我的代码。
最佳答案
只需创建一个隐式类,在类型参数为Numeric
的情况下提供附加方法:
class Example[X] {
def methodThatHaveAllImplementations(): Unit = println("all")
}
implicit class ExampleNumOps[N: Numeric](ex: Example[N]) {
def methodThatHaveOnlyNumerics(): Unit = println("num")
}
val x = new Example[Int]()
x.methodThatHaveOnlyNumerics()
x.methodThatHaveAllImplementations()
val y = new Example[String]()
y.methodThatHaveAllImplementations()
输出:
num
all
all
关于Scala 隐式特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49562438/