Closures vs java anonymous classes

vishalaries88
Neuling
Neuling
Beiträge: 1
Registriert: 18. Jul 2015 00:55

Closures vs java anonymous classes

Beitrag von vishalaries88 »

got from last years trial exam.
Can anyone explain this?

Name three ways in which Scala closures are different from anonymous classes in Java. Hint: think about what would
be different or difficult if you had to implement the following loopUntil control flow operator in Java:

def loopUntil(cond: =>Boolean)(body: =>Unit) =
while(!cond) {
body
}
def example() {
var i = 0
loopUntil(i == 100) {
println(i)
if (i == 50) return;
i += 1
}
println("Done.")
}

Banashri
Windoof-User
Windoof-User
Beiträge: 25
Registriert: 19. Dez 2013 02:55

Re: Closures vs java anonymous classes

Beitrag von Banashri »

I can see 2 problems.

1. i variable cannot be modified in Java, as it allows to access only final variables for closures.
2. if (i == 50) return; Not possible to break out of loop or return a value as a result of the containing method from within the lambda in Java.

ayushmaan_jain
Mausschubser
Mausschubser
Beiträge: 64
Registriert: 18. Okt 2014 11:11

Re: Closures vs java anonymous classes

Beitrag von ayushmaan_jain »

In java anonymous class must extends a super class or implement an interface

ddimitrov
Erstie
Erstie
Beiträge: 20
Registriert: 17. Jul 2015 16:28

Re: Closures vs java anonymous classes

Beitrag von ddimitrov »

Closures:
- are more concise;
- have non-local returns;
- reduce boiler-plate code for creating anonymous classes.

Antworten

Zurück zu „Archiv“