简体   繁体   中英

Object Initialization with an initializer block

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" }
                      ^

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
}

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM