Is there a way to declare a specified set of values in method parameter in Scala?

时间:2017-04-10 02:06:57

标签: java scala methods

Let say I have a method to get student_subject table queries based on status, and this status can be 'failed', 'passed', 'ongoing'.

How do I do it in a method rather than 3 different methods? Is it possible that I declare what type of accepting String in the method parameters?

1 个答案:

答案 0 :(得分:2)

Just use traits and singletons

sealed trait Status //sealed doesn't allow to extend this trait in another compilation unit
case object Failed extends Status
case object Passed extends Status
case object Ongoing extends Status

def getStidentSubject(status: Status) = status match {
   case Failed => ...
   case Passed => ...
   case Ongoing => ...
}

Alternatively you could just match strings but it's much less type-safe.

If you need more enum-like capabilities in Scala (preserving ADT's advantages) I'd recommend Enumeratum library.