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

Scala中的Currying与匿名函数

发布时间:2020-12-16 09:51:48 所属栏目:安全 来源:网络整理
导读:我在比较两种在 Scala中定义 higher-order function的方法: def f1(elem: Int)(other: Int) = (elem == other)def f2(elem: Int) = (other: Int) = (elem == other) 第一个使用currying而第二个使用anonymous function. 我想知道两种方法之间的区别在于Scal
我在比较两种在 Scala中定义 higher-order function的方法:

def f1(elem: Int)(other: Int) = (elem == other)

def f2(elem: Int) = (other: Int) => (elem == other)

第一个使用currying而第二个使用anonymous function.

我想知道两种方法之间的区别在于Scala如何实现它们以及哪种版本更可取?

解决方法

这些实现与Scala编译器完全不同. curried版本通过取消参数来解压缩到Java方法:

def f1(elem: Int,other: Int): Boolean = elem.==(other);

第二个版本是一个返回匿名函数(Function1)的方法,因此它们的签名完全不同.虽然它们通常可以在Scala代码中互换使用,但在第二个版本中生成的代码要多得多:

def f2(elem: Int): Function1 = (new <$anon: Function1>(elem): Function1);

  @SerialVersionUID(value = 0) final <synthetic> class anonfun$f2$1 extends scala.runtime.AbstractFunction1$mcZI$sp with Serializable {
    final def apply(other: Int): Boolean = anonfun$f2$1.this.apply$mcZI$sp(other);
    <specialized> def apply$mcZI$sp(other: Int): Boolean = anonfun$f2$1.this.elem$1.==(other);
    final <bridge> <artifact> def apply(v1: Object): Object = scala.Boolean.box(anonfun$f2$1.this.apply(scala.Int.unbox(v1)));
    <synthetic> <paramaccessor> private[this] val elem$1: Int = _;
    def <init>(elem$1: Int): <$anon: Function1> = {
      anonfun$f2$1.this.elem$1 = elem$1;
      anonfun$f2$1.super.<init>();
      ()
    }
  }

我只考虑在我明确希望使用Function1对象的情况下使用第二个版本.但是,我个人倾向于使用curried版本,因为你仍然可以通过部分应用第一个来获得Function1. curried版本同样强大,但在不需要时不会创建Function1对象.

scala> f1(1) _
res1: Int => Boolean = <function1>

(编辑:李大同)

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

    推荐文章
      热点阅读