Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert tuple to case class with default values

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

I want to convert a Tuple13 to a case class with a default value.

like image 641
BusyBee Avatar asked Jul 21 '26 11:07

BusyBee


1 Answers

Try providing an apply factory method in the companion

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

or perhaps implicit conversion

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

The strange looking $lessinit$greater$default$3 is a hacky way of accessing defaults based on Scala extra no-arg constructor plus default constructor parameters

like image 118
Mario Galic Avatar answered Jul 24 '26 00:07

Mario Galic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!