Scala: implicitly for an implicit class

Given:

implicit class Foo(val i: Int) { def addValue(v: Int): Int = i + v } 

Is it possible to apply any implicitly to it? I get an error message:

 <console>:14: error: could not find implicit value for parameter e: Foo implicitly[Foo] 
+5
source share
2 answers

An implicit class Foo(val i: Int) means that there is an implicit conversion from Int to Foo . Therefore, implicitly[Int => Foo] should work.

Think of it this way: if you could invoke Foo with implicitly[Foo] , which Foo did you expect to get? A Foo(0) ? A Foo(1) ? A Foo(2) ?

+6
source

For more information

implcitly keyword can be explained as follows

implitly [T] means returning an implicit value of type T in context

This means that to get Foo implicitly you need to create an implicit value in the scope

For instance,

  implicit class Foo(val i: Int) { def addValue(v: Int): Int = i + v } implicit val foo:Foo = Foo(1) val fooImplicitly = implicitly[Foo] // Foo(1) 

Also note that Foo itself is only a class,

But by putting an implicit keyword in front of the class definition,

The compiler creates an implicit function of type Int => Foo

0
source

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


All Articles