Advertisement
mehedi2022

Tuple & List _ Scala

Sep 13th, 2022 (edited)
717
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.34 KB | None | 0 0
  1. //Exercise: Imagine you're working on an application where you track all your expenses. You need to represent an expense that consists of a name and a cost – for example, a 5$ meal at McDonald's. How would you represent it in Scala?
  2.  
  3. val meal = ("McDonald's" , 5)
  4. val name = meal._1
  5. val cost = meal._2
  6. println (s"A $cost$$ meal at $name.")
  7.  
  8. //Exercise: How would you represent a database of flights in Scala as a list? The database is given below
  9.  
  10.             Departure, Destination, Price
  11.             --------------------------
  12.             Geneva, Vienna, 200
  13.             Vienna, London, 150
  14.             London, Geneva, 300
  15.            
  16.  
  17.  val flightsDatabase = List (
  18.      ( "Geneva" , "Vienna", 200)
  19.       ("Vienna" , "London", 150)
  20.       ("London" , "Geneva", 300)
  21.       )
  22.  
  23.  
  24. Homework: 1.  What's the difference between tuples and lists?
  25.  
  26. Tuples is a Type of data that consists of several Pieces of other data. On the Other hand list is most common type of collection in Scala. Represents an arbitrary number of Piece of data. All piece of data in list must be in the same type. A list has a variable size while a tuple has a fixed size. Tuples are typed like tupe._1, list is types list(0)
  27.  
  28. Lists are mutable(values can be changed) whereas tuples are immutable(values cannot be changed). This means that tuples cannot be changed while the lists can be modified. Tuples are more memory efficient than the lists.
  29. Tuple are of type Tuple1 , Tuple2 ,Tuple3 and so on. There is an upper limit of 22 for the element in the tuple in the Scala, if need more elements, then you can use a collection, not a tuple.
  30.  
  31. 2. When should we use tuples and when – lists?
  32.  
  33. In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method. In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are especially handy for returning multiple values from a method. For this benefit we use Tuples.
  34.  
  35. 3.Pick your favorite social network or messenger. What are the main types of data it is working with .
  36.  
  37. Most used social network Facebook. Mainly String type data also Photos and Video.
  38.  
  39. 4. Build a database of expenses for a personal budgeting app in Scala. Below, there is a list of expenses, and your task is to put it in a Scala variable:
  40.  
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement