Implicit parameter not found in functional application

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?

+3
source share
1

, 5 .

, , :

def print[T <% Number](value:T) {}

, .

def print2[T <% Number]: T => Unit = value => { }

. , . T .

print2(5)

, print2, 5 . T , 5 T => Number. , 5 Function1[T, Number], , T.

print2. :

print2(implicitly[Int => Number])
print2[Int]
(print2: Int => Unit)
val f: Int => Unit = print2

, print2, , (5) print2. , - :

print2(implicitly[Int => Number])(5)
print2[Int].apply(5)
(print2: Int => Unit)(5)
val f: Int => Unit = print2; f(5)

, , . , :

print2.apply(5)

print2, , T. T , Nothing. Nothing => Unit. , .

, print2, , .

+3

Source: https://habr.com/ru/post/1793746/


All Articles