1

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

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Shivam Sahil
  • 4,055
  • 3
  • 31
  • 62

1 Answers1

3

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")
Shivam Sahil
  • 4,055
  • 3
  • 31
  • 62