Right now I have a def
that returns a Tuple2[String, Int], or (String, Int).
def makeTuple(name: String, age: Int) : (String, Int) = {
(name, age)
}
val nameAge = makeTuple("test", 12)
println(nameAge._1) // prints test
println(nameAge._2) // prints 12
Ok this works, but Is there a way to give this tuple names?
For example:
println(nameAge.name)
println(nameage.age)
As jubobs mentioned we can do it like this:
Using the case class:
case class NameAge(name:(String), age:(Int))
def makeTuple(name: String, age:Int): NameAge = {
NameAge(name, age)
}
val nameAge = makeTuple("test",12)
println(nameAge.name, nameAge.age)
Using val:
def makeTuple1(name: String, age:Int): (String, Int) = {
(name, age)
}
val (name, age) = makeTuple1("test", 12)
println(name, age)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With