Currying to anonymous function in Scala

I compared two ways to define a higher order function in Scala:

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

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

The first uses currying , and the second uses an anonymous function .

I am wondering what is the difference between the two approaches in how Scala implements them and which version is preferable?

+4
source share
1 answer

The implementations are very different from the Scala compiler. The pocket version comes down to the Java method without looking at the parameters:

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

- , (a 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. , , Function1 . , Function1, .

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

Source: https://habr.com/ru/post/1669475/


All Articles