我有一个元组
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
在 scala 2.11.8
和 scala 2.12
中,case class
的伴生对象扩展了 FunctionN
,所以这会足够了:
Person tupled tuple
模式匹配
没有丑陋的 _N
方法的 new Person(tuple._1, tuple._2)
的类似模式匹配是:
tuple match { case (name, age) => Person(name, age) }
关于scala - 将 scala 元组打包到自定义类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17484384/