繁体   English   中英

Scala中匿名函数的隐式参数

[英]Implicit parameters of anonymous functions in Scala

我对匿名函数的隐式参数有些困惑。 希望有人会指出正确的方向。 这就是我所拥有的。 两个文件: Main.scalaFoo.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
  }
}

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

我希望看到Test: it works! 打印。 但是我遇到了一个编译错误:

$ 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

我想念什么吗?

更新

看起来我应该像这样导入我的隐式val:

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

这很好。

如果要在函数内部直接使用s ,则没有必要将其标记为隐式。

您可以通过这种方式解决此问题,

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

问题在于, FooFun的apply方法主体看不到implicit val s

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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