如何让构建器返回不同子类型的实例?

时间:2017-05-03 13:41:32

标签: scala

class Dog(name:String, age:Int) { def bark() = "woof" }

// complex dog builder
object DogBuilder {
   def  complexBuilder(name: String, age:Int) = 
       {new Dog(name + "A", age-1)}
}

// type Special identical constructor parameters, but has extra method
 class SpecialDog(name:String, age:Int) extends Dog(name:String, age:Int)      
 { def special_dog() = "special"}}

我对complex_builder进行了哪些修改,以便它还可以返回SpecialDog的实例?我怎么告诉编译器“它没关系,Dog和SpecialDog有相同的参数,所以可以使用相同的complexBuilder,但返回SpecialDog或Dog”。我理解complexBuilder必须以某种方式改变,但是..how / what?

我想要的是(psedo-code)

object DogBuilder {
    // a function that translates the inputs in some complex fashion
   def complexRules {(String, Int) => (String, Int)

    def  specialDog: specaalDog = new SpecialDog(..uses complexRules)
    def  regularDog: Dog = new Dog(..resuses same complexRules)


val specialDog: specialDog  = DogBuilder.specialDog("D", 5)
val dog: Dog= DogBuilder.regularDog("D", 5)

当然,由于类型擦除不会起作用,但模仿上述内容的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

好的,这是一个非常糟糕的问题。不好意思,朋友。它只是错误,拼写错误,它甚至无法远程编译(我看到一英里外的双括号等内容)。

认为这就是你想要的,虽然我不知道它与类型擦除有什么关系。对我来说,似乎你想在创建类的实例之前将complexFunction应用于参数。

class Dog(name: String, age: Int) {
  def bark() = "woof"
}

class SpecialDog(name: String, age: Int) extends Dog(name: String, age: Int) {
  def special_dog() = "special"
}

object DogBuilder {

  def complexRules(s: String, i: Int) = (s + "a", i + 1)

  def dog(name: String, age: Int): Dog = {
    val (newName, newAge) = complexRules(name, age)
    new Dog(newName, newAge)
  }

  def specialDog(name: String, age: Int): SpecialDog = {
    val (newName, newAge) = complexRules(name, age)
    new SpecialDog(newName, newAge)
  }

}