Scala: Requiring members on companion objects of abstract classes

Viewed 1377

I'd like to create an abstract class, and be able to add members to it that reference attributes of the implementing class's companion object. Something like this (Scala pseudocode):

abstract class Fruit(cultivar: String) {
    // How do I reference the implementing class's companion object here?
    def isTastyCultivar(): Boolean = Fruit.tastyCultivars.contains(cultivar)
}

// how do I implement what I am thinking of as "the abstract companion object"
abstract object Fruit {
    val tastyCultivars: Set[String]  // must be implemented
                                     // by the concrete object
}

class Apple(cultivar: String) extends Fruit(cultivar) {

}

object Apple extends Fruit{ // presumably this is not correct; 
                            // it needs to extend the FruitObject
                            // or whatever it is
    val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}

class Tomato(cultivar: String) extends Fruit(cultivar) {

}

object Tomato extends Fruit{
    val tastyCultivars = Set("Roma")
}

val a1 = new Apple("Red Delicious")
val a2 = new Apple("Honeycrisp")

a1.isTastyCultivar()  // should return true
a2.isTastyCultivar()  // should return false

val t1 = new Tomato("Roma")
val t2 = new Tomato("San Marzano")

t1.isTastyCultivar() // should return true
t2.isTastyCultivar() // should return false

Sorry if this is a dumb question, or if asked previously (I'm not confident in how to word this question so I couldn't easily search for it). Thanks in advance!

4 Answers
Related