Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Packing scala tuple to custom class object

Tags:

I have a tuple

val tuple = ("Mike", 40) 

and a case class

case class Person(name: String, age: Int) 

How can I pack my tuple to object of Person class? Are there any ways except this:

new Person(tuple._1, tuple._2) 

Maybe somesing like

tuple.asInstanceOf[Person] 

Thanks.

like image 863
Pavel Varchenko Avatar asked Jul 05 '13 08:07

Pavel Varchenko


1 Answers

tupled

You could convert Person.apply method to function and then use tupled method on function:

(Person.apply _) tupled tuple 

In scala 2.11.8 and scala 2.12 companion object of case class extends FunctionN, so this would be enough:

Person tupled tuple 

Pattern matching

An analogue of new Person(tuple._1, tuple._2) without ugly _N methods is the pattern matching:

tuple match { case (name, age) => Person(name, age) } 
like image 147
senia Avatar answered Oct 14 '22 20:10

senia