简体   繁体   中英

How to set default type in Scala Numeric Generic Function?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM