简体   繁体   English

Scala中匿名函数的隐式参数

[英]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 : 两个文件: 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
  }
}

And

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

I'm expecting to see Test: it works! 我希望看到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: 看起来我应该像这样导入我的隐式val:

// 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. 如果要在函数内部直接使用s ,则没有必要将其标记为隐式。

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 . 问题在于, FooFun的apply方法主体看不到implicit val s

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

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