The best place where we can use tuple is, when we want to return multiple values from a method or pass multiple values to a function. Because they aren’t a collection, they don’t have methods like map, filter, etc. Note: Technically, Scala 2.x tuples aren’t collections classes, they’re just a convenient little container. One approach is to access them by element number, where the number is preceded by an underscore, method tuple._i is used to access the ith element of the tuple. ![]() Operations on Scala Tuple Access element from tuple Currently there is an upper limit of 22 in the Scala and if we need more, then we will have to use a collection, not a tuple. Tuples can be of type Tuple1, Tuple2, Tuple3 and so on. Thus, the type of (1, “hello world”) is Tuple2. The type of a tuple depends upon the number of elements it contains and the types of those elements. Which is a syntactic sugar for the following- val t = new Tuple2(1, "hello world") An example of a tuple storing an integer, and a string value. Click here to know more about mutability and immutability. A tuples purpose is to combine a fixed and finite number of items together to allow the programmer to pass a tuple as a whole. This may be preferable instead of using a case class, particularly if we need to return unrelated values.In Scala, a tuple is a class that gives us a simple way to store heterogeneous items or different data types in the same container. We can use tuple.swap Method for Swapping the elements of a tuple. The foreach method takes function as a parameter and applies it to every element in the tuple, names. We can use productIterator() method to iterate over all the elements of a Tuple. ![]() Rock has wrong relation with Alice Iterating over a Scala tuple List(("Bob", "Father"), ("Jack", "Brother"), ("Rock", "Friend"))Ĭase _ => println(relation(2)._1 + " has wrong relation with Alice") Pattern matching is a mechanism for checking a value against a pattern.Īnother Example for pattern-matching a tuple: val relation = It is a great way to assign tuple elements to variables. The another approach to access elements of a tuple is pattern-matching. ![]() In Scala, a tuple is a class that gives us a simple way to store heterogeneous items or different data types in the same container.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |