代码之家  ›  专栏  ›  技术社区  ›  Andrey Tyukin

“缺少参数列表”中的反直觉建议-具有多个参数列表的方法的错误消息?

  •  1
  • Andrey Tyukin  · 技术社区  · 7 年前

    def foo(a: Int)(b: Int) = a + b
    foo
    

    它不编译,并生成以下错误消息:

    error: missing argument list for method foo
    Unapplied methods are only converted to functions when 
      a function type is expected.
    You can make this conversion explicit by writing 
    `foo _` or `foo(_)(_)` instead of `foo`.
    

    这个 foo _

    foo(_)(_)
    

    如前一条错误消息所示,我得到一条新的错误消息:

    error: missing parameter type for expanded 
    function ((x$1: <error>, x$2: <error>) => foo(x$1)(x$2))
    

    在什么情况下 foo(_)(_) -暗示应该是有用的, 它到底告诉我什么

    (1)噪声消除;我越是不断地编辑这个问题,它就越没有意义;科尔马是对的)

    1 回复  |  直到 7 年前
        1
  •  2
  •   Kolmar    7 年前

    类型 foo(_)(_) (Int, Int) => Int . 因此,如果指定该类型或在预期该类型的上下文中使用该类型,则它可以工作:

    scala> foo(_: Int)(_: Int)
    res1: (Int, Int) => Int = $$Lambda$1120/1321433666@798b36fd
    
    scala> val f: (Int, Int) => Int = foo(_)(_)
    f: (Int, Int) => Int = $$Lambda$1121/1281445260@2ae4c424
    
    scala> def bar(f: (Int, Int) => Int): Int = f(10, 20)
    bar: (f: (Int, Int) => Int)Int
    
    scala> bar(foo(_)(_))
    res2: Int = 30
    
    推荐文章