简体   繁体   中英

How are Scala closures implemented in Scala.NET?

As I understand it, Function types in Scala compile to instances of FunctionN . So that for example this example

List(1,2,3).filter(_ >= 2)

means

List(1,2,3).filter(new Function1[Int,Bool]{def apply(_$1:Int) = _$1 >= 2;})

How is this implemented in Scala.NET? As I understand it, .NET does not have statement-level anonymous classes. And the above solution depends on there being anonymous classes.

I don't know anything about Scala, but I don't see why that shouldn't be implemented the same way as C# closures, ie the following code:

new List<int>{1,2,3}.Where(i => i >= 2)

This code is implemented by creating a new function in the current class. If you really created a closure:

int max = 2;
var result = new List<int> { 1, 2, 3 }.Where(i => i >= max);

That would be implemented by creating a new class that contains the variable max along with the anonymous function.

EDIT:

I just tried compiling your code using Scala.Net and looking at the compiled code in Reflector gives this:

int[] numArray1 = new int[] { 1, 2, 3 };
List$.MODULE$.apply(new BoxedIntArray(numArray1)).filter(new $anonfun$1());

Where $anonfun$1 is a class that implements the Function1 interface and its apply() function looks like this:

public sealed override bool apply(int x$1)
{
    return (x$1 >= 2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM