Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to write a function with a generic AnyVal
    text
    copied!<p>I'm trying to get the following Scala code to compile:</p> <pre><code>// Something that Scala is very bad at: don't try and figure out if every type I *could* possibly use supports it, // just let me use it until I try a type that doesn't. Or at least have AnyValue provide an abstraction for all // Numeric Types (Interface) trait NumericValue[T] { def +(rhs : T, lhs : T) : T } implicit object ByteNumericValue extends NumericValue[Byte] { def +(rhs : Byte, lhs : Byte) : Byte = (rhs + lhs).toByte } implicit object ShortNumericValue extends NumericValue[Short] { def +(rhs : Short, lhs : Short) : Short = (rhs + lhs).toShort } implicit object IntNumericValue extends NumericValue[Int] { def +(rhs : Int, lhs : Int) : Int = rhs + lhs } implicit object LongNumericValue extends NumericValue[Long] { def +(rhs : Long, lhs : Long) : Long = rhs + lhs } implicit object BigIntNumericValue extends NumericValue[BigInt] { def +(rhs : BigInt, lhs : BigInt) : BigInt = rhs + lhs } def doMath[T &lt;: AnyVal](initializer : Long)(implicit Num : NumericValue[T]) : T = { Num.+(initializer.asInstanceOf[T], initializer.asInstanceOf[T]) } lazy val math = doMath[Short](0) </code></pre> <p>The idea here is that I need a way to make doMath operate on any Integer and thus a type with an addition operator. I want it to be agnostic of large number like BigInt or a very small number like Byte.</p> <p>When I try to compile this I get an error:</p> <pre><code>error: could not find implicit value for parameter Num: NumericValue[Short] lazy val math = doMath[Short](0) </code></pre> <p>Any ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload