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]
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.
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.
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.
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.
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)
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With