是否有更简洁的方法来编写此方法?优选地,我不需要匹配所有有效类型,而是允许每个具有*方法的Type.另外,有没有办法asInstanceOf[T]在最后不要求?
def expr_neg[T <: AnyVal](value: T): T = value match {
case int: Int => (int * -1).asInstanceOf[T]
case long: Long => (long * -1).asInstanceOf[T]
case float: Float => (float * -1).asInstanceOf[T]
case double: Double => (double * -1).asInstanceOf[T]
}
Run Code Online (Sandbox Code Playgroud)
使用Numeric Typeclass会更好:
def exprNeg[T:Numeric](value: T): T = {
val n = implicitly[Numeric[T]]
n.negate(value)
}
Run Code Online (Sandbox Code Playgroud)