Why is my implicit function parameter not working?

Here is my code snippet:

implicit def trick(s: String): String = s.toUpperCase    
def fun(s: String)(implicit f: String => String): String = f(s)        
println(s"String is ${fun("abc")}")

When I run it, it prints "abc" instead of "ABC". What am I doing wrong here?

PS

However, if I run the following code

implicit val n: Int = 100
def add(n1: Int)(implicit n2: Int) = n1 + n2
add(7)

all implicit magic works just fine.

+4
source share
1 answer

This will usually work. The compiler will implicitly convert the implicit method to a function through an eta extension. Let's say if for some reason I wanted to require an implicit one Int => List[Int].

implicit def trick(i: Int): List[Int] = List.fill(5)(i)

def fun(i: Int)(implicit f: Int => List[Int]): List[Int] = f(i)

scala> fun(4)
res5: List[Int] = List(4, 4, 4, 4, 4)

, String => String , Predef. =:=[String, String], String => String. , - . , , implicits:

implicit val trick: String => String = _.toUpperCase

scala> fun("abc")
<console>:19: error: ambiguous implicit values:
 both method $conforms in object Predef of type [A]=> <:<[A,A]
 and value trick of type => String => String
 match expected type String => String
       fun("abc")

, String => String, , . , .

case class Trick[A](f: A => A)

implicit val trick = Trick[String](_.toUpperCase)

def fun(s: String)(implicit t: Trick[String]): String = t.f(s)        

scala> println(s"String is ${fun("abc")}")
String is ABC
+7

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


All Articles