【发布时间】:2016-07-08 15:50:11
【问题描述】:
在 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)
【问题讨论】:
-
我更喜欢第一个,因为您不需要任何隐式和运行时强制转换,但这是一个偏好问题。
-
同意@Tuval,第二个绝对是矫枉过正
标签: scala class generics implicit