Java Reference
In-Depth Information
" bottles of beer"));
}
}
Here's how it looks in Scala:
object Beer {
def main(args: Array[String]){
2 to 6 foreach { n => println(s"Hello ${n} bottles of beer") }
}
}
It looks similar to the Java code but is less verbose. First, you can create a range using the
expression 2 to 6. Here's something cool: 2 is an object of type Int. In Scala everything is an
object; there's no concept of primitive types like in Java. This makes Scala a complete
object-oriented language. An Int object in Scala supports a method named to, which takes as
argument another Int and returns a range. So you could have written 2.to(6) instead. But
methods that take one argument can be written in an infix form. Next, foreach (with a lowercase
e) is similar to forEach in Java 8 (with an uppercase E). It's a method available on a range (here
you use the infix notation again), and it takes a lambda expression as argument to apply on each
element. The lambda expression syntax is similar to Java 8 but the arrow is => instead of ->. [ 2 ]
The previous code is functional: you're not mutating a variable as you did in our earlier example
using a while loop.
2 Note that in Scala the terminology “anonymous functions” or “closures” (interchangeable) is
used to refer to what Java 8 calls lambda expressions.
15.1.2. Basic data structures: List, Set, Map, Tuple, Stream, Option
Feeling good after a couple of beers to quench your thirst? Most real programs need to
manipulate and store data, so let's now look at how you can manipulate collections in Scala and
how that compares to Java 8.
Creating collections
Creating collections in Scala is simple, thanks to its emphasis on conciseness. To exemplify,
here's how to create a Map:
val authorsToAge = Map("Raoul" -> 23, "Mario" -> 40, "Alan" -> 53)
 
Search WWH ::




Custom Search