Pair And Triple
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 71 of 93.
Sometimes you need to group just two or three related values together without creating a full list. Kotlin provides Pair and Triple for exactly this purpose.
A Pair holds exactly two values. Create one using the Pair() constructor or the to keyword:
val coordinates = Pair(10, 20)
val person = "Alice" to 25 // Same as Pair("Alice", 25)Access the values using first and second:
val point = Pair(5, 8)
println(point.first) // 5
println(point.second) // 8A Triple works similarly but holds three values, accessed with first, second, and third:
val rgb = Triple(255, 128, 0)
println(rgb.first) // 255
println(rgb.second) // 128
println(rgb.third) // 0These are useful when a function needs to return multiple values, or when you want to group related data without defining a custom class. The values can be of different types, making them flexible for various situations.
Challenge
MediumWrite a function getMinMax that takes a list of integers and returns a Pair containing the minimum and maximum values, then formats them as a string.
Create a Pair where first holds the minimum value and second holds the maximum value from the list. Then return a formatted string using the pair's properties.
Parameters:
numbers(List<Int>): A list of integers with at least one element
Returns: A string in the format "Min: X, Max: Y" where X is the minimum value (first) and Y is the maximum value (second) from the Pair.
Input constraints: The input list is nonempty.
Try it yourself
fun getMinMax(numbers: List<Int>): String {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic Input12Lists Basics
List vs MutableListAccessing ElementsModifying ListsList MethodsPair And TripleRecap - Product ListRecap - Reversed ListPractice on your own: Kotlin playground