0

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, by-name implicits were backported to scala 2.13? So there is no need for Lazy type in shapeless? Saw the status is still 'PENDING' docs.scala-lang.org/sips/byname-implicits.html
@tribbloid By-name implicits were added in 2.13.0 github.com/scala/scala/releases/tag/v2.13.0 By-name implicits and shapeless.Lazy are not equivalent. I guess I met cases when one helped while the other didn't. Also you can write def foo(implicit tc: Lazy[TC[A]]): tc.value.Out = ??? but you can't write def foo(implicit tc: => TC[A]): tc.Out = ???. So Lazy is still necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.