简体   繁体   中英

Implicit parameters of anonymous functions in Scala

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM