Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Scala have object initialization like C#?

Object initialization in C#:

var foo = new Foo() { bar = 5 };

which is equivalent of

var foo = new Foo();
foo.bar = 5;

Does Scala have object initialization like C#?

like image 335
greenoldman Avatar asked Sep 18 '11 10:09

greenoldman


2 Answers

scala> class Foo { var bar: Int = _ }
defined class Foo

scala> var foo = new Foo() { bar = 5 }
foo: Foo = $anon$1@1ed00d1

scala> var realFoo = new Foo()
realFoo: Foo = Foo@1bedb0

You can see that the syntax works (in this case), but also that foo does not have type Foo. It's actually a new subtype of Foo which subclasses it with whatever is between the braces. In this case just the constructor with an additional assignment.

In the general case, the exact C# syntax will not work:

scala> class Foo { var bar: Int = _; var baz: String = _ }
defined class Foo

scala> var foo: Foo = new Foo { bar = 5, baz = "bam" }
<console>:1: error: ';' expected but ',' found.
       var foo: Foo = new Foo { bar = 5, baz = "bam" }

Instead you'll need to type:

scala> var foo: Foo = new Foo { bar = 5; baz = "bam" }
foo: Foo = $anon$1@1be20c

Foo constructor will run first, then the anonymous type constructor will run next.

I think this is what Kim and Alexey comments refer to.

I don't use C#, but it seems in C# this bit of syntax can only be used to initialize fields, while in Scala it was decided to use this syntax to extend the class like in Java.

like image 68
huynhjl Avatar answered Oct 12 '22 12:10

huynhjl


Scala does not have object initialization like C#, but Scala does not need it most of the time. There are factory methods for collections, which can easily substitute object initialization of C#'s collections. There are case classes with copy methods, which help with the initialization of the rest of the objects. There are anonymous classes, which help extending a class and initializing an instance of a class with all it's members at the same time.

like image 45
agilesteel Avatar answered Oct 12 '22 12:10

agilesteel