If I define a print function that accepts only numbers:
def print[T <% Number](value:T) {}
print: [T](value: T)(implicit evidence$1: (T) => java.lang.Number)Unit
I can call above:
print(5)
print(5.5)
print(6L)
But not with the line:
print("aaa")
<console>:7: error: could not find implicit value for evidence parameter of type (java.lang.String) => java.lang.Number
print("aaa")
Expected.
But if I define the print function as:
def print2[T <% Number]: T => Unit = value => { }
print2: [T](implicit evidence$1: (T) => java.lang.Number)(T) => Unit
Note that the implicit parameter is the first parameter, not the last.
If I try to manually determine the above function:
def print3[T](implicit f: (T) => java.lang.Number)(value:T):Unit = { }
<console>:1: error: '=' expected but '(' found.
def print3[T](implicit f: (T) => java.lang.Number)(value:T):Unit = { }
Basically the above is not a valid function definition, but the compiler creates it when I previously defined print2.
When I call print2 with Int:
print2(5)
<console>:7: error: type mismatch;
found : Int(5)
required: (?) => java.lang.Number
print2(5)
if I parameterize it:
print2[Int](5)
<console>:7: error: type mismatch;
found : Int(5)
required: (Int) => java.lang.Number
print2[Int](5)
It looks like it cannot find the implicit conversion from scala.Int => java.lang.Integer.
How can I redefine the print so that it returns functions and also appeals to implications correctly?
source
share