0

Could someone explain what is the difference (and why) between Syntax 1 & Syntax 2.

object Test extends App {
   def fun(provider: (String) => String) = {
     println(provider("xxx"))
   }

   //Syntax 1
   fun(MyObj.provider.giveString)
   //Syntax 2
   fun(x => MyObj.provider.giveString(x))
}

object MyObj {
   var provider = new StringProvider
}

class StringProvider {
   def giveString(param: String) = param + "_giveString"
}

Syntax 1 will create anonymous function that will capture reference to StringProvider, while syntax 2 will not. Why ? Could someone explain me that (or even better point to some documentation)

This is what scala generates. For Syntax 1:

public final class Test$$anonfun$1 extends AbstractFunction1 implements Serializable {
    public static final long serialVersionUID = 0L;
    private final StringProvider eta$0$1$1;

    public final String apply(String param) {
        return this.eta$0$1$1.giveString(param);
    }

    public Test Test$$anonfun$1(StringProvider eta$0$1$1) {
        this.eta$0$1$1 = eta$0$1$1;
    }
}

In case of Syntax 2:

public final class Test$$anonfun$2 extends AbstractFunction1 implements Serializable {
    public static final long serialVersionUID = 0L;

    public final String apply(String x) {
        return .MODULE$.provider().giveString(x);
    }
}

Regards, Pawel

Pawel Niezgoda
  • 165
  • 1
  • 6
  • "Syntax 1 will create anonymous function that will capture reference to StringProvider, while syntax 2 will not." - where did you get that from? – The_Tourist Dec 06 '16 at 19:40
  • Possible duplicate of [What is the eta expansion in Scala?](http://stackoverflow.com/questions/39445018/what-is-the-eta-expansion-in-scala) – cchantep Dec 06 '16 at 19:50
  • @YoungSpice edited my question and posted code that scala generates for both calls – Pawel Niezgoda Dec 06 '16 at 20:04
  • @virtuss That is super similar to another question posted just a few hours ago: http://stackoverflow.com/questions/40999190/scala-compilation-anonymized-function You're not the same person, are you? :-) – The_Tourist Dec 06 '16 at 20:24
  • @YoungSpice it's not me...but I agree...looks the same. Thanks for pointing – Pawel Niezgoda Dec 06 '16 at 20:42

0 Answers0