【问题标题】:apply function with implicit parameter requires explicit argument带有隐式参数的应用函数需要显式参数
【发布时间】:2014-09-06 06:09:56
【问题描述】:

我不明白为什么这不起作用:

case class Expression extends Node[Doube] {

   def apply(implicit symbolTable: Map[String,Double]) = value
}

请注意,值是在 Node 中定义的,也带有隐式符号表参数。

当我尝试像这样调用它时:

implicit val symbolTable = Map("a"->1, "b"->2)
//and x is an Expression, then:

x() // does not compile (can't find implicit) but 
x(symbolTable) // works fine

奇怪的是:

x.value // works fine too

如果我这样写申请:

def apply()(implicit symbolTable: Map[String,Double]) 

它有效,但我不明白为什么我需要这样做......

任何指针?

【问题讨论】:

    标签: scala implicit


    【解决方案1】:

    spec 区分值转换和方法转换。

    x 是一个值。对于您的带有两个参数列表的示例,x() 是一种具有一个参数列表的方法类型,即隐式提供的参数列表。

    对于您的原始示例,使用一个隐式参数列表,x() 无法提供所需的参数。 (不是“隐式未找到”。)

    scala> def f(implicit s: String) = 42
    f: (implicit s: String)Int
    
    scala> f
    <console>:9: error: could not find implicit value for parameter s: String
                  f
                  ^
    
    scala> f()
    <console>:9: error: not enough arguments for method f: (implicit s: String)Int.
    Unspecified value parameter s.
                  f()
                   ^
    

    对于要提供的隐式,您不能提供参数列表。

    对于你奇怪的x.value,显然value 是一种带有一个隐式参数列表的方法。

    更多:

    scala> object x { def apply(implicit s: String) = 42 }
    defined object x
    
    scala> x.apply
    <console>:9: error: could not find implicit value for parameter s: String
                  x.apply
                    ^
    
    scala> implicit val s: String = "hi"
    s: String = hi
    
    scala> x.apply
    res1: Int = 42
    
    scala> x()
    <console>:10: error: not enough arguments for method apply: (implicit s: String)Int in object x.
    Unspecified value parameter s.
                  x()
                   ^
    

    当您像上面那样编写x.apply 时,它会提供括号将其转换为应用程序,提供隐式参数,或者在上下文需要时尝试将其转换为函数。

    【讨论】:

    • 是的,value 是一种带有一个隐式参数列表的方法,但 apply 也是如此,为什么它们的行为方式不同?
    • 你没有在任何地方写x.apply
    • 这不是 x() 调用的吗?
    • 我的意思是你没有写x.apply,这与写x.apply()x()不一样。 x.apply 是一个方法,而不是一个值。您可以通过添加括号 x.apply()x.apply(_) 来获得一个值以获取一个函数。
    猜你喜欢
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多