Corey
Corey

Reputation: 1059

Scala - Cleaner way of writing generic numeric operation method

Is there a cleaner way of writing this method? Preferably, I wouldn't need to match against all valid Types and instead permit every Type that has the * method. Also, is there a way to not require asInstanceOf[T] at the end?

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]
}

Upvotes: 2

Views: 175

Answers (2)

Lukas Wegmann
Lukas Wegmann

Reputation: 478

In addition to @melps answer, it is also possible to use the arithmetic operators provided by Numeric.Implicits:

import Numeric.Implicits._

def f[T: Numeric](x: T) = -x

Which is pretty cool, but unfortunately never mentioned in the Scala docs. This also works for Ordering:

import Ordering.Implicits._

def g[T: Ordering](x: T) = x < x

Upvotes: 3

melps
melps

Reputation: 1247

You would be much better off using the Numeric Typeclass:

  def exprNeg[T:Numeric](value: T): T = {
    val n = implicitly[Numeric[T]]
    n.negate(value)
  }

Upvotes: 5

Related Questions