简体   繁体   中英

Scala 2.13 Case Class: Union of multiple case classes?

I have 3 case classes in Scala:

case class Teacher(name: String, subject: String, age: Int)
case class Student(name: String, subject: String, section: String, class: Int)
case class School(user: Teacher | Student)

In the third case class, the User could either be Teacher or Student but it has to be only one of them. How can I achieve the same syntactically in Scala 2.13?

Edit 1: As suggested in comments, Either does seem convenient but what if:

case class School(user: Teacher | Student | Principal)

Edit 2:

If I use a sealed trait as suggest in comments:

sealed trait SchoolUser
case class Student(name: String, subject: String, section: String, `class`: Int)
  case class Teacher(name: String, subject: String, age: Int)
  case class Principal(name: String, year: Int)

  case object Student extends SchoolUser
  case object Teacher extends SchoolUser
  case object Principal extends SchoolUser

  case class School(user: SchoolUser)

  val school = School(user = ???)

  println("Complete")

But I am confused on how to instantiate the case class as in line:

val school = School(user = ???) // Principal(name="ABC",year=2022)

Edit 4: Finally got all the answers

As suggested in the comments, for two cases Either works fine however for Three or More an ADT would suit with a sealed trait:

sealed trait SchoolUser
  case class Student(name: String, subject: String, section: String, `class`: Int) extends SchoolUser
  case class Teacher(name: String, subject: String, age: Int) extends SchoolUser
  case class Principal(name: String, year: Int) extends SchoolUser


  case class School(user: SchoolUser)

  val schoolPrincipal:SchoolUser = Principal("Name",123)

  println("Complete")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM