简体   繁体   中英

scala: default values for function with type parameters; used in partial applied context

How to specify default values for the type parameter in this context?

def increase[T: Numeric](x: T, y: T): T = implicitly[Numeric[T]].plus(x, y)

val inc = increase _

Output:

C:\\Sources\\scala\\main.scala:12: error: could not find implicit for evidence parameter of type Numeric[Nothing] val inc = increase _

increase has a generic type parameter. When you attempt to resolve the method to a function, it is implicitly trying to lookup the type T for which it needs to resolve the method. Since you haven't specified any type , it attempts to look up Numeric[Nothing] and finds out there is no such implicit available in scope.

What you need is to explicitly specify the type T for each resolution:

scala> val intInc = increase[Int] _
inc: (Int, Int) => Int = <function2>

scala> val doubleInc = increase[Double] _
doubleInc: (Double, Double) => Double = <function2>

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