私はタプルを持っています
val tuple = ("Mike", 40)
そしてケースクラス
case class Person(name: String, age: Int)
タプルを Person クラスのオブジェクトにパックするにはどうすればよいですか? これ以外の方法はありますか:
new Person(tuple._1, tuple._2)
多分何かのような
tuple.asInstanceOf[Person]
ありがとう。
私はタプルを持っています
val tuple = ("Mike", 40)
そしてケースクラス
case class Person(name: String, age: Int)
タプルを Person クラスのオブジェクトにパックするにはどうすればよいですか? これ以外の方法はありますか:
new Person(tuple._1, tuple._2)
多分何かのような
tuple.asInstanceOf[Person]
ありがとう。
組んだ
Person.applyメソッドを関数に変換してから、関数でメソッドを使用できtupledます。
(Person.apply _) tupled tuple
extendsscala 2.11.8のscala 2.12コンパニオン オブジェクトなので、これで十分です。case classFunctionN
Person tupled tuple
パターンマッチング
new Person(tuple._1, tuple._2)醜いメソッドなしの類似物_Nは、パターン マッチングです。
tuple match { case (name, age) => Person(name, age) }
さらに抽象化できる小さな「ただの楽しみ」バージョン。もちろん、shapelessの助けを借りて:
import shapeless._
import Tuples._
case class Person(name: String, age: Int)
val tup = ("Alex", 23)
val personIso = Iso.hlist(Person.apply _, Person.unapply _)
personIso.from(tup.hlisted)