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]
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]
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
© 2022 - 2024 — McMap. All rights reserved.
implicitly[Foo](4)
will returnres0: Foo = Foo@5d5eef3d
. – Bolenval foo: Foo = 4
compiles. – Chiliasm