加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala currying和类型推断

发布时间:2020-12-16 18:18:44 所属栏目:安全 来源:网络整理
导读:我试图弄清楚如何在 Scala中使用currying. 在以下代码段中: object Foo { def foo(a:Int)(b:Int)(c:Int) : Int = a + b + c def main(a:Array[String]) { val f = foo(1)(2) _ def g : Int = Int = foo(1)(2) // def h = foo(1)(2) println(f(3)) println(g
我试图弄清楚如何在 Scala中使用currying.

在以下代码段中:

object Foo {

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

  def main(a:Array[String]) {

    val f = foo(1)(2) _ 
    def g : Int => Int = foo(1)(2) 
    // def h = foo(1)(2) 

    println(f(3))
    println(g(3))
    // println(h(3))
  }
}

f和g工作的定义,h的定义不是:

/home/vlad/Desktop/b.scala:9: error: missing arguments for method foo in object Main;
follow this method with `_' if you want to treat it as a partially applied function
    def h = foo(1)(2)

这是非法的原因是什么?在我看来,Scala应该能够弄清楚在调用foo(1)(2)之后你会留下一个Int =>诠释.

解决方法

这是有意的.如果它被允许(某些语言确实允许),那么当你忘记放置一个参数时,这将使它工作,而不是你期望的编译时错误.这种情况经常发生,scala作者决定在这里进行权衡并禁止这种表示法.

马丁在他的书中讲到了这一点,请参阅“为什么尾随下划线?” http://www.artima.com/pins1ed/functions-and-closures.html#8.7

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读