2

Yesterday I was reading a paper called: How Scala Experience Improved Our Java Development.

Inside the Object Initialization section, it says:

The idiomatic Scala technique for instantiating an object (which does not expose all relevant parameters via constructor arguments) is to create an anonymous subclass with an initializer block which calls additional statements [Odersky et al.]:

I have been doing some tests:

class B {
  var x1: String = "B"

  def setText(text: String) {
    x1 = text   
  }

  override def toString = x1
}

I don't really understand why I can do:

scala> new B{setText("new Text")}
res23: B = new Text

but I can't do:

scala> new B{ setText "new Text" }
<console>:1: error: ';' expected but string literal found.
       new B{ setText "new Text" }
                      ^

2 Answers 2

12

This hasn’t got much to do with the initialiser block. It’s just that the sugaring syntax

a b

means

a.b

and not

a(b)

Or in the general case

obj meth arg

is sugar for

obj.meth(arg)

with arg being optional.

If you want to specify this without the parentheses, you’ll have to write the receiving object before the method:

new B { this setText "new Text" }

If, for whatever reason, you want to save characters, you could add a self-type alias:

new B { o =>
  o setText "new Text"
  o setTitle "a Title"
  o setSomeOtherArgument someArg
}
Sign up to request clarification or add additional context in comments.

Comments

4

The "operator notation" requires an explicit receiver. For example:

print("hello");

Will work, but:

print "hello"

Won't.

Again this will work, and print "hello"

Predef print "hello"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.