- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
val initialization before superclass constructor
Mon, 2010-06-28, 06:54
I've noticed that Scala 2.8 seems to no longer initialize fields before
calling the superclass constructor, unlike 2.7.
Consider the following REPL code:
---code---
class C1 {
val field = "C1"
println("Hi, I'm " + field)
}
class C2 extends C1 {
override val field = "C2"
}
new C1
new C2
---end code---
In Scala 2.7.7, this code prints:
---output---
Hi, I'm C1
Hi, I'm C2
---end output---
This is what I intend.
However, in 2.8.0.RC6, this code instead prints:
---output---
Hi, I'm C1
Hi, I'm null
---end output---
This is *not* what I intend, and it seems to be because C2 overrides the
generated method 'field', but doesn't initialize its generated field
'field' until after C1's constructor is called. As a result, field
'field' is null -- neither "C1" nor "C2" -- at the time C1's constructor
is called.
Is this behavior intentional? If so, how should I access potentially
overridden vals in a constructor?
http://scala-programming-language.1934581.n4.nabble.com/Constructor-vooo...
-jason
On Mon, Jun 28, 2010 at 7:54 AM, Alex Hvostov wrote:
> I've noticed that Scala 2.8 seems to no longer initialize fields before
> calling the superclass constructor, unlike 2.7.
>
> Consider the following REPL code:
>
> ---code---
> class C1 {
> val field = "C1"
> println("Hi, I'm " + field)
> }
>
> class C2 extends C1 {
> override val field = "C2"
> }
>
> new C1
> new C2
> ---end code---
>
> In Scala 2.7.7, this code prints:
>
> ---output---
> Hi, I'm C1
> Hi, I'm C2
> ---end output---
>
> This is what I intend.
>
> However, in 2.8.0.RC6, this code instead prints:
>
> ---output---
> Hi, I'm C1
> Hi, I'm null
> ---end output---
>
> This is *not* what I intend, and it seems to be because C2 overrides the
> generated method 'field', but doesn't initialize its generated field
> 'field' until after C1's constructor is called. As a result, field
> 'field' is null -- neither "C1" nor "C2" -- at the time C1's constructor
> is called.
>
> Is this behavior intentional? If so, how should I access potentially
> overridden vals in a constructor?
>