import scala.io.Source
val list = Source.fromFile("/etc/lsb-release").getLines().toList
val hash = list.map(_.split("=")).map {case Array(x,y) => (x,y)}.toMap
println(hash)
The ruby version:
hash = {}
File.read("/etc/lsb-release").each_line do |s|
s.strip!
(key,value) = s.split("=")
hash[key] = value
end
p hash
If you have Source.fromFile("/etc/lsb-release").getLines() without .toList you will get an Iterator. Then it won’t matter that you have two map calls because Iterator is lazy and will only iterate once over all lines when you call .toMap, instead of once per method call.
Yes, but that comes from inheritance structure, that’s why scaladoc is invaluable
ok, difference is present between Iterator and Iterable(which contains iterator), but practically usage wise, similar, , (but iterator is part of lazy computation which is quite interesting in stream of data…)
So instead of iterating over all elements it just returns a new Iterator that will apply function f to every element that comes out of the first Iterator.
Is not the compiler, is just the implementation. Iterators are lazy (as Jasper showed) thus all operations just create a new Iterator that knows how to process the elements once you start calling things like next
However, since they are mutable, it is not safe to share them. Because once you consume them once they are gone.
This is also the reason why they don’t have groupBy that won’t work since it would be impossible to create a Map[K, Iterator[V]] without those inner Iterators already being consumed.