Scala函数参数:类与函数泛型类型,例如f(classOf [Foo]," bar")vs f [Foo](" bar")

时间:2016-07-08 15:50:12

标签: scala class generics implicit

在Scala中,通常的做法是将类类型作为泛型传递或明确传递它们吗?

例如,我创建了一个辅助函数来创建一个Java对象,该对象接受源异常,目标异常和第三个参数(我只是在这个例子中使用一个字符串)。在Scala中哪一个更好的做法:

exceptionTranslation(classOf[FooException], classOf[BarException], "blah")

def exceptionTranslation(sourceClazz: Class[_ <: Throwable], targetClazz: Class[_ <: Throwable], message: String) = new Translation()
  .withSource(sourceClazz)
  .withTarget(targetClazz)
  .withMessage(message)

或者

exceptionTranslation[FooException, BarException]("blah")

def exceptionTranslation[Source <: Throwable, Target <: Throwable](message: String)(
implicit source: ClassTag[Source], target: ClassTag[Target]) = new Translation()
  .withSource(source.runtimeClass.asInstanceOf[Class[Source]])
  .withTarget(target.runtimeClass.asInstanceOf[Class[Target]])
  .withMessage(message)

1 个答案:

答案 0 :(得分:1)

我认为只是风格问题。他们都是正确的。就个人而言,我会选择更直观,更短,功能最少的那个。

提取类的文本名称的示例:

import scala.reflect._
def bar[F](x: Class[F]) = x.getName

def foo[X:ClassTag] = implicitly[ClassTag[X]].runtimeClass.getName

def foobar[X](implicit ctag: ClassTag[X]) = ctag.runtimeClass.getName

用法:

> bar(classOf[Double]) // This one has better Java interop 
res: String = "double"

> foo[Double]  // This looks slightly less verbose when calling 
res: String = "double"

> foobar[Double]
res: String = "double"