How do I declaratively create a list in Scala?

In C #, I can declare a list declaratively, in other words declare its structure and initialize 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 (i.e. feel free to use a different type of collection), is it possible to do something similar in Scala 2.8?

UPDATE

Adapting the Thomas code from below I believe this is the closest 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)) 
+4
source share
4 answers

Adapting the Thomas code from below I believe this is the closest 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 slightly different from how C # code behaves, because we provide an explicit constructor with default values, rather than using the no args constructor and set the properties later, but the end result is comparable.

+1
source

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)) 
+20
source
 val users = User("tom", 12) :: User("bill", 23) :: Nil 

You can also use the Scelas tupel class:

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

Or you can create objects without using an explicit class defined in your compilation unit, this way

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

Source: https://habr.com/ru/post/1339026/


All Articles