Home > Enterprise >  Scala 2: Generic function that doubles a number
Scala 2: Generic function that doubles a number

Time:07-31

Multiplying x and 2 doesn't work. Scala version is 2.13.8.

import Integral.Implicits._
object hello {
  def f[T:Integral](x: T): T = x * 2
  val x: Int = 1
  f(x)
}
type mismatch;
  found : Int(2)
  required: T
    def f[T:Integral](x: T): T = x * 2

CodePudding user response:

You need to convert 2 into a T.

Thankfully, the instance of the Integral typeclass for T (which is passed implicitly thanks to [T: Integral] has a fromInt method which can convert an Int like 2 into a T:

def f[T: Integral](x: T): T = {
  val two = implicitly[Integral[T]].fromInt(2)  // summons the typeclass instance
  x * two
}

CodePudding user response:

Adding to what Levi mentioned, you'll need to import:

import scala.math.Integral.Implicits.infixIntegralOps 

Still, you can simplify it to just:

def f[T: Integral](x: T): T = x * Integral[T].fromInt(2)

Taking advantage of the Integral companion object's apply method which takes an implicit of Integral[T] and returns it. It's exactly what implicitly does, only implicitly is more generic.

  • Related