簡體   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