scala - 将泛型类型约束为特定类型

dvm*_*lls 1 scala

我经常处理java中包含以下内容的东西:

def printDbl(d:Double) { println("dbl: " + d) }
def printInt(i:Int) { println("int: " + i) }
Run Code Online (Sandbox Code Playgroud)

当然,我想把它包装成一些scala,最终看起来像这样:

def print[T:Manifest] (t:T) {
  if (manifest[T] <:< manifest[Int]) { printInt(t.asInstanceOf[Int]) ; return }
  if (manifest[T] <:< manifest[Double]) { printDbl(t.asInstanceOf[Double]) ; return }

  throw new UnsupportedOperationException("not implemented: " + manifest[T])
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行以下内容时,我得到一个运行时异常:

print(1)
print(2.0)
print("hello")
Run Code Online (Sandbox Code Playgroud)

我似乎记得有一种方法可以在编译时捕获它,但我似乎无法谷歌它.也许是一些聪明的隐含转换?

dhg*_*dhg 6

你为什么不利用方法重载并像这样写你的Scala包装器?:

object Printer {
  def print(d: Double) { printDbl(d) }
  def print(i: Int) { printInt(i) }
}
Run Code Online (Sandbox Code Playgroud)

这很简单,并提供了所需的行为:

import Printer._
print(1.)          // dbl: 1.0
print(1)           // int: 1
print("hello")     // compile-time type error
Run Code Online (Sandbox Code Playgroud)