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

val initialization before superclass constructor

1 reply
Alex Hvostov
Joined: 2010-06-15,
User offline. Last seen 42 years 45 weeks ago.

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?

Jason Zaugg
Joined: 2009-05-18,
User offline. Last seen 38 weeks 5 days ago.
Re: val initialization before superclass 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?
>

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