Tuples are lightweight collections that let you group a few related values together without creating a full class. They're perfect for returning multiple values from a function or temporarily bundling data.
// Java uses records (Java 14+) instead of tuplesrecordGuitarInfo(Stringmodel,intstrings,Stringseries){}GuitarInfoguitar=newGuitarInfo("RG350DXZ",6,"RG Series");Stringmodel=guitar.model();// Access fieldintstrings=guitar.strings();// Access field
// Kotlin provides Pair and Triplevalguitar=Triple("RG350DXZ",6,"RG Series")// Access by positionvalmodel=guitar.firstvalstrings=guitar.secondvalseries=guitar.third// Destructuringval(m,s,sr)=guitar
typeGuitarInfo=[string,number,string];constguitar:GuitarInfo=["RG350DXZ",6,"RG Series"];// Access by indexconstmodel=guitar[0];conststrings=guitar[1];// Destructuringconst[m,s,sr]=guitar;
// Dart 3.0+ has native records(String,int,String)guitar=("RG350DXZ",6,"RG Series");// Access by positionStringmodel=guitar.$1;intstrings=guitar.$2;// Destructuringvar(m,s,sr)=guitar;
letguitar=("RG350DXZ",6,"RG Series")// Access by indexletmodel=guitar.0letstrings=guitar.1// Destructuringlet(m,s,sr)=guitar
# Create tupleguitar=("RG350DXZ",6,"RG Series")# Access by indexmodel=guitar[0]strings=guitar[1]# Destructuringm,s,sr=guitar
Tuples make it easy to return multiple values from a function without creating a custom class. This is especially helpful for simple cases where you just need to bundle a few values together temporarily.
For example, suppose you want a function that returns both a person's name and age. Without tuples, you'd need to create a class just for this simple task. With tuples, you can return both values directly:
// Java uses records (Java 14+)recordPersonInfo(Stringname,intage){}publicstaticPersonInfogetNameAndAge(){returnnewPersonInfo("Alice",25);}// UsagePersonInfoperson=getNameAndAge();Stringname=person.name();intage=person.age();System.out.println(name+" is "+age);// Alice is 25
fungetNameAndAge():Pair<String,Int>{returnPair("Alice",25)}// Destructuring makes it easyval(name,age)=getNameAndAge()println("$name is $age")// Alice is 25
functiongetNameAndAge():[string,number]{return["Alice",25];}const[name,age]=getNameAndAge();console.log(`${name} is ${age}`);// Alice is 25
// Dart 3.0+ records(String,int)getNameAndAge(){return("Alice",25);}var(name,age)=getNameAndAge();print('$name is $age');// Alice is 25
funcgetNameAndAge()->(String,Int){return("Alice",25)}let(name,age)=getNameAndAge()print("\(name) is \(age)")// Alice is 25
defget_name_and_age()->tuple[str,int]:return("Alice",25)name,age=get_name_and_age()print(f"{name} is {age}")# Alice is 25
Tuples are a simple, lightweight solution for returning multiple values when you don't need the overhead of a full class structure.