Reputation: 67
Recently, I have become interested in implicit functions. In the documentation, we can see several examples of using this property, but I think I do not quite understand how it works.
For example, we can read that implicit T0 => R
is actually
trait ImplicitFunction1[-T0, R] extends Function1[T0, R] {
override def apply(implicit x: T0): R
}
After writing the function below
val func = {implicit x: Int => 2*x}
I tried to use it in this way
implicit val x: Int = 3
println(func)
But it doesn't seem to work (only the <function1>
type is returned, it looks like apply
hasn't been used at all). If I had a method for it, it would work fine
def func(implicit x: Int) = 2*x
I'm not sure what I'm missing here.
Upvotes: 0
Views: 621
Reputation: 51648
Implicit function types work in Dotty
https://dotty.epfl.ch/docs/reference/contextual/implicit-function-types.html
https://dotty.epfl.ch/blog/2016/12/05/implicit-function-types.html
In Scala 2 func
has type Int => Int
instead of absent implicit Int => Int
(aka given Int => Int
).
implicit x: Int => ???
is just a shorthand for x: Int => { implicit val _x: Int = x; ???}
.
Out of all new implicit
(aka given
) features in Dotty only by-name implicits were backported to Scala 2.13.0.
Upvotes: 5