Why is it allowed to point to constructor parameters?

This code

class Foo(str: String) {
    val len = str.length
    def getLen = len
    def getStr = str}

will be compiled into

public class Foo implements ScalaObject
{

    private final int len;
    private final String str;
    public Foo(String str)
    {
        this.str = str;
        super();
        len = str.length();
    }

    public String getStr()
    {
        return str;
    }

    public int getLen()
    {
        return len();
    }

    public int len()
    {
        return len;
    }

    public int $tag()
        throws RemoteException
    {
        return scala.ScalaObject.class.$tag(this);
    }
}

But this code

class Foo(str: String) {
    val len = str.length
    def getLen = len
}

will be compiled into

public class Foo implements ScalaObject
{

    private final int len;

    public Foo(String str)
    {
        len = str.length();
    }

    public int getLen()
    {
        return len();
    }

    public int len()
    {
        return len;
    }

    public int $tag()
        throws RemoteException
    {
        return scala.ScalaObject.class.$tag(this);
    }
}

Why is there no private member in the Foo class?

private final String str;

Is this some kind of optimization?

Why is it allowed to point to constructor parameters. Why does not a compile-time error occur for the string " def getStr = str"?

+3
source share
2 answers

In Scala, constructor parameters are visible from anywhere inside the class, I see it more as “object parameters”. In the second fragment, it was not compiled to create a class attribute for it simply because you do not reference it outside the constructor - it is not needed.

+3
source

, , - , . , , , .

+1

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


All Articles