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?
答案 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.