This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
First of all, WHAT is a tuple? | |
In Ceylon it's represented as a typed linked list with a not so easy signature | |
as we will see later on. | |
But let's first get the picture here. Why are tuples useful. Well, sometimes you want to return 2 | |
or more objects from a method. Now you NEED to write a wrapper class for this whereas with these | |
generic Tuple classes, you can just construct them like any ordinary object. You only need | |
to provide the correct type parameters. | |
In Java and Scala Tuples are modelled a bit differently. A tuple with 2 elements could look like | |
public class Tuple2<A, B> { | |
private A first; | |
private B second; | |
public Tuple2(final A first, final B second) { | |
this.first = first; | |
this.second = second; | |
} | |
public A getFirst() { | |
return first; | |
} | |
public B getSecond() { | |
return second; | |
} | |
} | |
Usage of such a tuple would be | |
Tuple2<String, Integer> nameAndAge = new Tuple2<String, Integer>("Robby", 37); | |
**/ | |
/** | |
The tuples demo prints | |
Robby | |
Robby | |
37 | |
37 | |
<null> | |
**/ | |
void tuples_demo() { | |
//Below we use the syntactic sugar syntax to create a tuple (Strongly recommended). | |
[String, Integer] tuple1 = ["Robby", 37]; | |
/** | |
Below we use the fully qualified type declaration of a tuple like above | |
class Tuple<out Element, out First, out Rest=[]> | |
So you first specify the Union type of the tuple => "String | Integer" | |
Next you specify the type of the First element => "String" | |
Finally you recursively specify the same for the remainder (rest) => Tuple<Integer, Integer> | |
**/ | |
Tuple<String| Integer, String, Tuple<Integer,Integer>> tuple2 = ["Davy", 37]; | |
print(tuple1.first); | |
print(tuple1.get(0));//should be the same as first | |
print(tuple1.last); | |
print(tuple1.get(1)); //should be the same as last | |
print(tuple1.get(4)); //should print null | |
} |
No comments:
Post a Comment