将元组转换为具有默认值的案例类

问题描述 投票:3回答:1
case class Person(first: String, last: String, full: String = "blah")

val one = Person("Rachel","Green")
// one: Person = Person(Rachel,Green,blah)

val tuple1 = ("Ross","Geller")
// tuple1: (String, String) = (Ross,Geller)

Person tupled tuple1
// <console>:15: error: type mismatch;  found : (String, String)  required: (String, String, String

我想将Tuple13转换为具有默认值的案例类。

scala tuples case-class
1个回答
2
投票

尝试在同伴中提供apply工厂方法

object Person {
  def apply(t: (String, String)): Person = Person(t._1, t._2)
}
Person(tuple1)   // res2: Person = Person(Ross,Geller,blah)

或者可能是隐式转换

implicit def tupledWithDefaults(t: (String, String)) = (t._1, t._2, Person.$lessinit$greater$default$3)
Person.tupled(tuple1)   // res2: Person = Person(Ross,Geller,blah)

外观怪异的$lessinit$greater$default$3是一种基于Scala extra no-arg constructor plus default constructor parameters的默认访问方法,很骇人听闻>

© www.soinside.com 2019 - 2024. All rights reserved.