![]() List(1, 2, 3) map squared applies the function squared to the elements of the list, returning a new list, perhaps List(1, 4, 9). See Also Effective Scala has opinions about Options. Pattern matching fits naturally with Option. GetOrElse lets you easily define a default value. We would suggest that you use either getOrElse or pattern matching to work with this result. We want to multiply the number by two, otherwise return 0. How do we work with it?Ī first instinct might be to do something conditionally based on the isDefined method. Now our data appears trapped in this Option. Scala> val numbers = Map("one" -> 1, "two" -> 2) Option tells you that the method might not return what you’re asking for. Let’s look at an example of how Option is used: Option itself is generic and has two subclasses: Some or None The basic interface for Option looks like: Option is a container that may or may not hold something. Maps can themselves contain Maps or even functions as values. Map() also uses that variable argument syntax we learned back in Lesson #1: Map(1 -> "one", 2 -> "two") which expands into Map((1, "one"), (2, "two")) with the first element being the key and the second being the value of the Map. This looks like special syntax but remember back to our discussion of Tuple that -> can be used to create Tuples. See Also Effective Scala has opinions about destructuring bindings (“unpacking” a tuple). Tuple has some special sauce for simply making Tuples of 2 values: -> ![]() Unlike case classes, they don’t have named accessors, instead they have accessors that are named by their position and is 1-based rather than 0-based. HostPort: (String, Int) = (localhost, 80) Numbers: = Set(5, 1, 2, 3, 4)Ī tuple groups together simple logical collections of items without using a class. Sets do not preserve order and have no duplicates :9: error: value update is not a member of List Lists preserve order, can contain duplicates, and are immutable. ArraysĪrrays preserve order, can contain duplicates, and are mutable. See Also Effective Scala has opinions about how to use collections.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |