【问题标题】:Why are types of a named function different from an anonymous one in scala [duplicate]为什么命名函数的类型与scala中的匿名函数不同[重复]
【发布时间】:2013-07-05 05:27:45
【问题描述】:

在scala中,命名函数定义为:

scala> def addOne(x: Int): Int = x+1
addOne: (x: Int)Int

scala> :type addOne
(x: Int)Int

还有一个匿名的:

scala> val addOne = (x:Int) => x+1
addOne: Int => Int = <function1>

scala> :type addOne
Int => Int

为什么它们的类型看起来不同?

为什么不能将命名函数作为参数传递给另一个函数?

不应该从类型和一阶行为的角度统一对待吗?

【问题讨论】:

    标签: function scala anonymous


    【解决方案1】:

    def addOne(x: Int): Int 不是 Scala 中的函数。这是某个对象的方法。

    val addOne = (x:Int) =&gt; x+1 这样的函数是FunctionN 类型的对象(在本例中为Function1),方法为apply

    在 scala 中可以将方法用作函数 - 编译器可以从方法中创建函数,例如:

    scala> List(1, 2, 3).map((1).+) // or just `1+`
    res0: List[Int] = List(2, 3, 4)
    

    在这种情况下,对象1 的方法+ 用作函数x =&gt; (1).+(x)

    scala> List(1, 2, 3).foreach(println)
    1
    2
    3
    

    对象Predef的方法println用作函数s =&gt; Predef.println(s)

    2.10 版本开始,您不能在方法上使用:type

    scala> def addOne(x: Int): Int = x+1
    addOne: (x: Int)Int
    
    scala> :type addOne
    <console>:9: error: missing arguments for method addOne;
    follow this method with `_' if you want to treat it as a partially applied function
           addOne
           ^
    

    【讨论】:

      猜你喜欢
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 2014-05-29
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2013-05-27
      • 1970-01-01
      相关资源
      最近更新 更多