4

When I using java there are something like double bracket initialization that actually make some runtime trade off. In scala I discover the simple way to initiate object property like

val button1: Button = new Button
button1.setText("START")
button1.setPrefWidth(100)

Which can be rewriten to

val button2: Button = new Button {
setText("PAUSE")
setPrefWidth(100)
}

Is these make any difference from performance or something else?

1 Answer 1

4

The difference is that in the first case you instantiate a new Button object and set its properties to some values (text = "START" and width = 100) and in the second case you create an anonymous class that inherits from Button and initialize its properties in its anonymous initializer (or constructor, not sure - Java's anonymous classes cannot have constructors).

The second case can be roughly rewritten like this (if it weren't an anonymous class):

class MyButton extends Button {
  //constructor
  setText("START")
  setPrefWidth(100)
}

And when you call new MyButton you get an instance of MyButton with text set as "START" and prefWidth set as 100.

If you come from Java background consider this analogy:

Button button = new Button() {
    //anonymous initializer
    {
        setText("START");
        setPrefWidth(100);
    }
};
Sign up to request clarification or add additional context in comments.

4 Comments

I recently read this post: stackoverflow.com/questions/924285/… so, is there any performance impact with that initialization in scala?
I mean, is scala implementation of anonymous class differ from java?
I have actually no idea about the performance of this. I think I'll try to measure it soon
Ok, just tested. Initialization of 1000 Button() objects took approximately ~78 ms on my laptop. 1000 Button{} objects took approximately ~397 ms. 10 measurements for each case. So yes, there is a performance impact but it's not that critical to reject this type of initialization

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.