How to set default type in Scala Numeric Generic Function?

92 views Asked by At

My question is pretty simple.

I've read some possible duplicates like Scala: specify a default generic type instead of Nothing, Default generic type on method in scala

But these cases are not same as mine.

// define
def sum[T](name: String)(implicit numeric: Numeric[T]): ...
def sum(name: String) = sum[Double](name)

// use
val a = sum[Long]("name...") // It's OK.
val b = sum("name...") // ERROR: ambiguous reference to overloaded definition

I want to use sum("....") same as sumDouble

I really appreciate it if you can give me any hint.

1

There are 1 answers

0
Alexey Romanov On

For this case you can use this trick:

trait A {
  def sum[T](name: String)(implicit numeric: Numeric[T]): String = numeric.zero.toString
}

object B extends A {
  def sum(name: String): String = sum[Double](name)
}

// use
val a = B.sum[Long]("name...")
val b = B.sum("name...") 

Working example

Of course you can import B.sum to refer to the function just as sum.