Scala: implicitly to implicit class
Asked Answered
S

2

5

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]
Sansbury answered 21/11, 2016 at 22:38 Comment(2)
implicitly[Foo](4) will return res0: Foo = Foo@5d5eef3d.Bolen
That's because of the same reason that val foo: Foo = 4 compiles.Chiliasm
C
7

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)?

Chiliasm answered 21/11, 2016 at 22:43 Comment(0)
E
1

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

Explosive answered 22/11, 2016 at 15:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.