Search code examples
scalagenericsscala-3

How to make a generic numeric method in scala 3?


I've seen this question answered before, but for scala 2 using implicit. However, scala 3 lacks the implicit keyword, which leaves me at square one.

So, how would I go about making a generic method like this toy example:

def add2[T](number: T) = number + 2

that is, how do I write a method that works equally well for Double, Float, Int, and so on?


Solution

  • As new in Scala 3 doc mentions - implicits (and their syntax) have been heavily revised and now you can achieve this with using clause:

    def add2[T](number: T)(using num: Numeric[T]): T = {
        import num._
        number + num.fromInt(2)
    }