- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
What's the difference between this two class argument definition?
Wed, 2010-12-15, 09:35
What's the difference between this two class argument definition?
class Button(label: String){ }
class Button(val label: String){ }
Are they equivalent?
class Button(label: String){ }
class Button(val label: String){ }
Are they equivalent?
Wed, 2010-12-15, 09:57
#2
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?
Wed, 2010-12-15, 15:37
#3
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
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