简体   繁体   中英

Scala shortest equivalent to c# LINQ

I need to create a bunch of new objects in scala What is the shortest equivalent for the following C# code?

var n = 100;    
var persons = Enumerable.Range(1, n).Select(x=>new Person(x)).ToList();

and whats wrong with this?

val persons: List[Person] = (1 to n) map (new Person(_))

Use List.range :

List.range(1, n + 1).map(new Person(_))

Or as Lee suggested:

(1 to n).map(new Person(_)).toList

Calling toList is required because (1 to n).map(new Person(_)) produces an IndexedSeq[Person] . Note also that the type of 1 to n is Range.Inclusive and that it is different to the type of List.range(1, n + 1) which is List[Int] .

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