lundi 25 avril 2016

Factory method example in scala repl giving error

I am unable to run below code in Scala repl. This is a reproduction from Scala cookbook example provided by Alvin Alexander

This works fine when compiling (scalac) and executing (scala). Can you please tell me how I can make this example work on repl as well? Thanks a lot for your help!

trait Animal {
    def speak
}
object Animal {
    private class Dog extends Animal {
        override def speak = {
            println("woof")
        }
    }

    private class Cat extends Animal {
        override def speak { println("meow") }
    }
    def apply(s: String):Animal = {
        if (s == "dog") return new Dog
        else return new Cat
    }

}


# repl
Animal("dog") 

# compiling
object test {
    def main(args: Array[String]){
        Animal(args(0)).speak
    }
}

Aucun commentaire:

Enregistrer un commentaire