Scala factory pattern returns unusable abstract type

Posted by GGGforce on Programmers See other posts from Programmers or by GGGforce
Published on 2013-10-28T08:56:25Z Indexed on 2013/10/28 10:01 UTC
Read the original article Hit count: 343

Filed under:
|

Please let me know how to make the following bit of code work as intended. The problem is that the Scala compiler doesn't understand that my factory is returning a concrete class, so my object can't be used later. Can TypeTags or type parameters help? Or do I need to refactor the code some other way? I'm (obviously) new to Scala.

trait Animal
trait DomesticatedAnimal extends Animal
trait Pet extends DomesticatedAnimal {var name: String = _}
class Wolf extends Animal
class Cow extends DomesticatedAnimal
class Dog extends Pet

object Animal {
    def apply(aType: String) = {
        aType match {
            case "wolf" => new Wolf
            case "cow" => new Cow
            case "dog" => new Dog
        }
    }
}

def name(a: Pet, name: String) {
  a.name = name
  println(a +"'s name is: " + a.name)
}                                               

val d = Animal("dog")                                                     
name(d, "fred") 

The last line of code fails because the compiler thinks d is an Animal, not a Dog.

© Programmers or respective owner

Related posts about scala

Related posts about factory-method