Phil Hunt
Phil Hunt

Reputation: 527

How do I create a List of classes?

I am trying to create a List of classes, like this:

abstract class Animal {
    def name = this.getClass.getName
    def say: String
}
class Dog extends Animal {
    def say = "Woof" 
}
class Cat extends Animal {
    def say = "Meow"
}
val animalClasses = List(Dog, Cat)

This falls over on the last line, with the error message:

Zoo.scala:18: error: not found: value Dog

Note that I could create a List of instances of classes easily with List(new Dog(), new Cat()), but that's not what I want.

Upvotes: 2

Views: 3570

Answers (1)

John K
John K

Reputation: 1285

There you go:

scala> List(classOf[Dog],classOf[Cat])
res1: List[Class[_ >: Cat with Dog <: Animal]] = List(class Dog, class Cat)

As per this:

The predefined function classOf[T] returns a runtime representation of the Scala class type T.

Upvotes: 4

Related Questions