私はタプルを持っています
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 class
FunctionN
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)