1

I'm a bit stuck with implicit parameters of anonymous functions. Hope somebody'll point me the right direction. Here is what I have. Two files: Main.scala and Foo.scala:

// Foo.scala
trait Fun[-A, +B] extends (A => B)

trait ImplicitString[+B] {
  def withString(block: String => B)(implicit s: String): B = block(s)
}

object FooFun extends Fun[String, String] with ImplicitString[String] {
  def apply(x: String): String = withString { implicit s =>
    x + s
  }
}

And

// Main.scala
object Main extends App {
  implicit val s = "it works!"
  println(FooFun("Test:"))
}

I'm expecting to see Test: it works! printed. But I got a compilation error:

$ scalac Main.scala Service.scala
Service.scala:8: error: could not find implicit value for parameter s: String
  def apply(x: String): String = withString { implicit s =>
                                        ^
one error found

Am I missing something?

UPDATE:

Looks like I should have imported my implicit val like this:

// Foo.scala
import Main._
...

This works fine.

1
  • (A => B) is nothing but Function[-A, +B], so your trait Fun really isn't needed. Commented Apr 9, 2014 at 14:45

1 Answer 1

1

If you are going to use s directly inside function, there's no point of marking it as implicit.

You can fix this in this way,

object FooFun extends Fun[String, String] with ImplicitString[String] {
  def apply(x: String)(implicit s1:String): String = withString { s =>
    x + s
  }
}

The problem is, implicit val s is not visible to the apply method body of FooFun.

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

2 Comments

I tried this. This can't be compiled since FooFun is no longer implements Fun trait: there is no apply: String => String function in FooFun. There is just: apply: String => (String => String).
Folks, please, try to compile it before +1ing.

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.