The disadvantage of such POJOs is the clutter they create as we browse classes in Eclipse package explorer. They are present because the language (Java) doesn't provide tools to model these really ad-hoc types. As a result these become permanent types. They are not a model of real world into Object Oriented System being designed. They are not even part of the Design.
Scala comes with a nice solution to this problem with the Tuple type. In Scala you can group a set of values together to create a Tuple object. Scala compiler based on the type of values and the order will infer the Type of the Tuple. So you get to return multiple values from a method and probably pass multiple values together to a function. Or in a function you need to temporarily group certain values together. It saves you unnecessary classes and removes clutter and allows you concentrate on business logic.
A tuple is a finite element container of possibly heterogeneous types.Like lists, tuples are immutable, but unlike lists, tuples can contain different types of elements. To instantiate a new tuple that holds some objects, just place the objects in parentheses, separated by commas. Once you have a tuple instantiated, you can access its elements individually with a dot, underscore, and the one-based index of the element.
val pair = (10,"Apples") println(pair._1) println(pair._2)
We just created a tuple and assigned a reference named pair to it. The tuple contains two elements. The first being an Int and second a String. You can access elements of a tuple with one based index interface methods such as _1,_2,_3. Scala infers the type of the tuple to be Tuple2[Int, String], and gives that type to the variable pair. The actual type of a tuple depends on the number of elements it contains and the types of those elements. Scala library has defined Tuple classes upto Tuple22. Tuple2 class for example is a Tuple2[A,B] parametrized class which infers the type of the elements to be Int and String in the case above.
Now lets say if you have a class Circle which needs to return its Center. Immediately you will think about a class named Point with x and y values. In Scala you can get away with defining a Point class by just returning a tuple.
class Circle { private val radius = 20 def center():(Int, Int) = { var x = 10 var y = 20 (x, y) } }You can create tuples in scala with a "->" method.
scala> 1->2 res0: (Int, Int) = (1,2)How this works is out of scope for this blog post. Using -> method is common for defining key value pairs in a map.
scala> val m = Map(1->2, 3->4) m: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4)Tuples are also useful while doing Pattern Matching, For Comprehensions in Scala. I will try and discuss their use when I visit Pattern Matching and For Comprehensions.