Search code examples
scalainitializationblockpostfix-notation

Scala postfixOps feature not operating inside an object block


Suppose I have the following file test.scala

import scala.language.postfixOps

trait Trait {
  var v = 'a

  def update(x :Symbol):Unit = {
    v = x
  }
}

object x extends Trait
x update 'b
// value of x.v is now 'b, as expected

object y extends Trait {
  update('c)
}
// value of y.v is now 'c, as expected

object z extends Trait {
  // this causes compilation failure:
  update 'd
}

When I run the above code, the postfix invocation inside the object z init block fails:

$ scala test.scala
test.scala:23: error: ';' expected but symbol literal found.
update 'd

I haven't had any luck trying to find an explaination for why scala fails to understand the postfix inside the object init block, or what (if anything) can be done to make it work.


Solution

  • You intended infix:

    object z extends Trait { this update 'd }
    

    Postfix means;

    scala> trait Trait { var v = 'a; def update(x :Symbol) = v = x; def reset = v = 'a }
    defined trait Trait
    
    scala> object z extends Trait { this update 'd }
    defined object z
    
    scala> z reset
    warning: there were 1 feature warning(s); re-run with -feature for details
    
    scala> z.v
    res1: Symbol = 'a