Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: implicitly to implicit class

Given:

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

is it possible apply to it any implicitly? I get an error here:

<console>:14: error: could not find implicit value for parameter e: Foo
       implicitly[Foo]
like image 513
Randomize Avatar asked Nov 21 '16 22:11

Randomize


People also ask

What is Scala implicit class?

Scala 2.10 introduced a new feature called implicit classes. An implicit class is a class marked with the implicit keyword. This keyword makes the class's primary constructor available for implicit conversions when the class is in scope. Implicit classes were proposed in SIP-13.

What is implicit conversion in Scala?

Implicit conversions in Scala are the set of methods that are apply when an object of wrong type is used. It allows the compiler to automatically convert of one type to another. Implicit conversions are applied in two conditions: First, if an expression of type A and S does not match to the expected expression type B.

How does Scala pass implicit value?

In simpler terms, if no value or parameter is passed to a method or function, then the compiler will look for implicit value and pass it further as the parameter. For example, changing an integer variable to a string variable can be done by a Scala compiler rather than calling it explicitly.

Where does Scala look for Implicits?

Unless the call site explicitly provides arguments for those parameters, Scala will look for implicitly available given (or implicit in Scala 2) values of the correct type. If it can find appropriate values, it automatically passes them.


2 Answers

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

Think about it like this: if you could summon a Foo with implicitly[Foo], which Foo would you expect to get? A Foo(0)? A Foo(1)? A Foo(2)?

like image 177
Jasper-M Avatar answered Oct 08 '22 09:10

Jasper-M


For further details,

implcitly key word can be explained as following

implitly[T] means return implicit value of type T in the context

Which means, to get Foo implicitly you need to create an implicit value in the scope

For example,

 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 implicit key word in front of class definition,

Compiler creates an implicit function of type Int => Foo

like image 44
Wonpyo Park Avatar answered Oct 08 '22 11:10

Wonpyo Park