As you said, enumerations tend to give rise to case discrimination … after all, how else are you going to make sense of the different values of the enumeration?
But in OOP, we already have a perfectly good way of doing case discrimination: polymorphic message dispatch. That's all you need. You don't need case
or switch
or even if
or for
or while
. Smalltalk doesn't have any of those, it doesn't have any conditionals, it doesn't have any loops, it doesn't have any case discrimination. Only polymorphic message dispatch. And it works just fine that way.
So, where you would do something like this in a language without polymorphic message dispatch:
enum Weekday {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
def weekdayToString(day: Weekday) = match day {
case Weekday.Monday => "Monday"
case Weekday.Tuesday => "Tuesday"
case Weekday.Wednesday => "Wednesday"
case Weekday.Thursday => "Thursday"
case Weekday.Friday => "Friday"
case Weekday.Saturday => "Saturday"
case Weekday.Sunday => "Sunday"
}
def printWeekday(day: Weekday) = println(weekdayToString(day))
printWeekday(Weekday.Wednesday)
// Wednesday
In a language with polymorphic message dispatch, you would do it like this:
sealed trait Weekday
object Monday extends Weekday { override def toString() = "Monday" }
object Tuesday extends Weekday { override def toString() = "Tuesday" }
object Wednesday extends Weekday { override def toString() = "Wednesday" }
object Thursday extends Weekday { override def toString() = "Thursday" }
object Friday extends Weekday { override def toString() = "Friday" }
object Saturday extends Weekday { override def toString() = "Saturday" }
object Sunday extends Weekday { override def toString() = "Sunday" }
def printWeekday(day: Weekday) = println(day)
printWeekday(Wednesday)
// Wednesday
(That is actually runnable Scala code.)
In other words: you can always replace an enumeration with case discrimination with an inheritance hierarchy with polymorphism.
Interestingly, Scala actually does have enumerations, but there are efforts for removing them from the language. They just don't add any significant expressive power to a language which already has objects.