Volodymyr Bezuglyy
Volodymyr Bezuglyy

Reputation: 16785

Why it is allowed to point to constructors parameters?

This code

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

will be compiled to

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 to

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 there is no a private member in class Foo?

private final String str;

Is it some sort of optimization?

Why it is allowed to point to constructor's parameters. Why there is no compile-time error for line "def getStr = str"?

Upvotes: 3

Views: 255

Answers (2)

Germán
Germán

Reputation: 4565

In Scala, constructor parameters are visible from anywhere within the class, I see it more like "object parameters". In your second snippet it wasn't compiled to create a class attribute for it simply because you're not referencing it outside the constructor - it is not needed.

Upvotes: 3

Ashalynd
Ashalynd

Reputation: 12563

Well, according to Odersky book, the constructor is the only place where you can match fields to the constructor arguments. If you don't do it there will be no variable seen outside the constructor.

Upvotes: 1

Related Questions