2

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] } 
1
  • 1
    If you are interested in numerical computations using scala, you should check out github.com/non/spire. It contains a much richer set of typeclasses than just numeric. Commented Jul 11, 2015 at 16:16

2 Answers 2

5

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) } 
Sign up to request clarification or add additional context in comments.

Comments

3

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.