Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name tuple variables in Scala

Tags:

tuples

scala

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)
like image 590
Mr.Turtle Avatar asked Jan 01 '23 17:01

Mr.Turtle


1 Answers

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)
like image 186
Raman Mishra Avatar answered Jan 14 '23 13:01

Raman Mishra