exam ws16-17 topic 1b

Moderatoren: pmueller, SE - Design and Construction

typ
Windoof-User
Windoof-User
Beiträge: 32
Registriert: 5. Nov 2016 19:06

exam ws16-17 topic 1b

Beitrag von typ » 9. Jul 2018 19:17

Hi,
I am stuck on this exercise. What are differences between closures in Scala and Java 8. I found this explanation for closures: https://alvinalexander.com/scala/how-to ... p-examples. I know in Java you can only pass final variables into a anonymous class (or lambda interface). Thats why you can use something like

Code: Alles auswählen

final String[] muSt = {"mutable string"}
to get the same thing as in scala.

I compiled the code from the exam and it returns 1, no matter how often I do ...(f(f(f(f(x), which seems logical but why is the code so complicated then?

What would be a correct answer for the question?

Additional code:

Code: Alles auswählen

import org.junit.Test;

public class Tester {

    @Test
    public void lala() {
        final String[] muSt = {"mutable string"};
        TesterIfc la = () -> muSt[0];
        System.out.println(la.ifc());
        muSt[0] = "other string";
        System.out.println(la.ifc());
    }

    interface TesterIfc {
        String ifc();
    }
}


eichberg
Moderator
Moderator
Beiträge: 448
Registriert: 25. Sep 2007 12:12
Kontaktdaten:

Re: exam ws16-17 topic 1b

Beitrag von eichberg » 10. Jul 2018 08:26

Hi,

you basically gave the correct answer already: a Scala closure can access mutable variables while a Java one doesn't. In Java, you have to use the idiom shown in your example, which is not definitively not ideal.

Antworten

Zurück zu „Software Engineering - Design and Construction“