Aladdin - Scala Bugtracking
[#689] project: compiler priority: high category: missing feature
submitter assigned to status date submitted
Burak Martin won't fix 2006-08-03 18:03:06.0
subject confusing constructors
code
package fk

case object  ParseException extends Throwable {}

class RexParser(input: Iterator[char]) {

  init()
  var ch = '%'; // illegal character that we *should* never see
  
  def next: char =  {
    if(input.hasNext)
                do { 
                  ch = input.next; 
                  System.out.println("'"+ch+"'"); // DEBUG
                } while (Character.isWhitespace(ch));
    System.out.println("meet this cute character, ch = "+ch); // DEBUG
    return ch;
  }
  def init(): this.type  = { 
    System.out.println("init()"); 
    this.next; 
    System.out.println("after init() ch is now ch == '"+ch+"'"); 
    this; 
  }
  
  def nextEvent: Object = {
    System.out.println("nextEvent(), ch = "+ch); // DEBUG
    if (Character.isJavaIdentifierStart(ch)) {
      Console.println(1); System.exit(-1); null
    } else {
      System.out.println("huh? I don't like this character ch == '"+ch+"'");
      throw ParseException
    } 
  }
  
}

object fk {
  def main(args:Array[String]) = {
    val z:Seq[Char] = "port['int']"
    val p = new RexParser(z.elements)
    p.nextEvent
  }
}
what happened
Just because the call to init() comes before the vardef, the compiler assigns the '%' character to \
the field after running init(). This leads to unpredictable behavior.
[emir@lamppc31 /tmp]$ java -classpath .:/home/emir/sbaz/lib/scala-library.jar fk.fk
init()
'p'
meet this cute character, ch = p
after init() ch is now ch == 'p'
nextEvent(), ch = %
huh? I don't like this character ch == '%'
Exception in thread "main" fk.ParseException$
        at fk.ParseException$.(fk.scala)
        at fk.RexParser.nextEvent(fk.scala:33)
        at fk.fk$.main(fk.scala:43)
        at fk.fk.main(fk.scala)
what expected either (1) all field assignments be done before methods are called in the constructor, or (2) warnings that side-effects of method called from the constructor might be undone by subsequent assignments.
[back to overview]
Changes of this bug report
Martin  edited on  2006-08-14 16:43:28.0
I agree that this is a trap. But it does not have an easy fix. Note that Scala and Java's behavior are exactly the same in this case. Why does it not have an easy fix: "either (1) all field assignments be done before methods are called in the constructor" what if a field assignment involes a method call? "or (2) warnings that side-effects of method called from the constructor might be undone by subsequent assignments." This might be worth it, but ot would require a complicated and necessary incomplete flow analysis.