This page is no longer maintained — Please continue to the home page at www.scala-lang.org

What's the difference between this two class argument definition?

3 replies
xideveloper
Joined: 2010-12-15,
User offline. Last seen 1 year 44 weeks ago.
What's the difference between this two class argument definition?

 class Button(label: String){ }
 class Button(val label: String){ }
Are they equivalent?
Stephen Tu
Joined: 2010-02-24,
User offline. Last seen 42 years 45 weeks ago.
Re: What's the difference between this two class argument defin
On Wed, Dec 15, 2010 at 12:35 AM, xi developer <xideveloper36@gmail.com> wrote:
What's the difference between this two class argument definition?

 class Button(label: String){ }
 class Button(val label: String){ }
Are they equivalent?

this should give some insight:

$ scala
Welcome to Scala version 2.8.0.r0-b20101102110129 (Java HotSpot(TM) Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class Button(label: String)
defined class Button

scala> val b = new Button("HI")
b: Button = Button@1955c3

scala> b.label
<console>:8: error: value label is not a member of Button
       b.label
         ^

scala> class Button(val label: String)
defined class Button

scala> val b = new Button("HI")      
b: Button = Button@f0b51d

scala> b.label
res1: String = HI


H-star Development
Joined: 2010-04-14,
User offline. Last seen 2 years 26 weeks ago.
Re: What's the difference between this two class argument defin

-------- Original-Nachricht --------
> Datum: Wed, 15 Dec 2010 10:35:50 +0200
> Von: xi developer
> An: scala-user@listes.epfl.ch
> Betreff: [scala-user] What\'s the difference between this two class argument definition?

speaking java:

> What's the difference between this two class argument definition?
>
> class Button(label: String){ }

this is a constructor parameter

>
> class Button(val label: String){ }

this is a public final String

>
> Are they equivalent?

Cay Horstmann
Joined: 2009-09-04,
User offline. Last seen 42 years 45 weeks ago.
Re: What's the difference between this two class argument defin

2010/12/15 xi developer :
> What's the difference between this two class argument definition?
>
>  class Button(label: String){ }
>  class Button(val label: String){ }
> Are they equivalent?

No. One way to get some insight into this is to run javap -private Button

You'll find that in the first case, label is not turned into a
field--there is no need to because it is nowhere referenced. In the
second case, label turns into a private final field with a public
getter.

Cheers,

Cay

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland