开发者

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"?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜