Rupert Bates
Rupert Bates

Reputation: 3061

How do I declaratively create a list in Scala?

In C# I can declare a list declaratively, in other words declare its structure and initialise it at the same time as follows:

var users = new List<User>
            {
                new User {Name = "tom", Age = 12}, 
                new User {Name = "bill", Age = 23}
            };

Ignoring the differences between a List in .Net and a List in Scala (ie, feel free to use a different collection type), is it possible to do something similar in Scala 2.8?

UPDATE

Adapting Thomas' code from below I believe this is the nearest equivalent to the C# code shown:

class User(var name: String = "", var age: Int = 0)

val users = List(
  new User(name = "tom", age = 12), 
  new User(name = "bill", age = 23))

Upvotes: 4

Views: 1359

Answers (4)

Rupert Bates
Rupert Bates

Reputation: 3061

Adapting Thomas' code from below I believe this is the nearest equivalent to the C# code shown:

class User(var name: String = "", var age: Int = 0)

val users = List(
  new User(name = "tom", age = 12), 
  new User(name = "bill", age = 23))

It is subtly different to the way the C# code behaves because we are providing an explicit constructor with default values rather than using the no args constructor and setting properties subsequently, but the end result is comparable.

Upvotes: 1

gruenewa
gruenewa

Reputation: 1676

val users = User("tom", 12) :: User("bill", 23) :: Nil

You could also use Scalas tupel class:

val users = ("tom", 12) :: ("bill", 23) :: Nil

Upvotes: 4

ryskajakub
ryskajakub

Reputation: 6431

Or you can create objects without use of explicit class defined in your compilation module this way

List(
   new {var name = "john"; var age = 18},
   new {var name = "mary"; var age = 21}
)
Note, that this code has some serious drawback, it will create an anonymous class per each new.

Upvotes: 3

Thomas Rawyler
Thomas Rawyler

Reputation: 1095

What about:

case class User(name: String, age: Int)

val users = List(User("tom", 12), User("bill", 23))

which will give you:

users: List[User] = List(User(tom,12), User(bill,23))

Upvotes: 20

Related Questions