There are two ways to access a tuple’s elements. The declaration t1 is just syntactic sugar for a Tuple: val t1 = Tuple2(1, "A") A tuple of int and String would look like: val t1 = (1, "A") If we just place some elements inside parentheses, we get a Tuple. Scala 2.x has classes named Tuple2, Tuple3 … up to Tuple22. We can pass this as a whole, and there’s no need to declare a class separately. We can find the complete list of methods of Scala Map in the ScalaDoc.Ī Tuple is a collection that gives us a way to store different items in the same container. When the key exists, it returns the value in Some context, whereas if the key does not exist, it returns None: Map(1 -> "a", 2 -> "b").get(1) // Some(a) Its signature in the Map trait is as follows: def get(key: K): Option The get method returns an optional value. Let’s see how these methods work: Map(1 -> "a", 2 -> "b").keys // res0: Iterable = Set(1, 2) Returns an iterable containing all values of the Map Returns an iterable containing all keys of the Map The methods for working with maps are bit different: No. By default, an immutable version of the map is imported: val immutableMap = Map(1 -> "a", 2 -> "b") val mutableMap = (1 -> "a", 2 -> "b") Scala provides mutable and immutable versions of it. While printing the value of x and xs, we find that x is the head of the list, and xs is the remaining list.Ī Map is a collection of key/value pairs where keys are always unique. In the above example, we can represent the numbersList using the x :: xs notation. Nil represents an empty list: val numbersList: List = 1 :: 2 :: 3 :: 4 :: Nil // List of Integers A Scala list containing elements can be represented using x :: xs, where x is the head and the xs is the remaining list. This List class comes with two implementing case classes, scala.Nil and scala.::, that implement the abstract members isEmpty, head, and tail. Val emptyList: List = List() // Empty List We can, for example, declare a list of integers: val numbersList: List = List(1, 2, 3 ,4) Most other operations are O(n) though this includes length, append, reverse, and also the index-based lookup of elements. This means that many operations have either a constant memory footprint or no memory footprint at all.Ī list has O(1) prepend and head/tail access. It also implements structural sharing of the tail list.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |