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


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的实例?我如何告诉编译器"没关系,狗和规格有相同的论点,因此可以使用相同的复杂构造器,但返回SpeciaLdog或Dog"。我了解complexBuilder必须以某种方式改变,但是..什么?

什么?

我想要的是(psedo代码(

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)

当然,由于类型的擦除而无法使用,但是模仿上述最好的是什么?

好吧,这是一个非常不好的问题。不好意思,朋友。它只是充满了错误,错别字,它甚至无法远程编译(我看到诸如从一英里外的双括号之类的东西(。

i 认为这是您想要的,尽管我不知道这与类型擦除有什么关系。对我来说,似乎您想在创建类实例之前将复杂功能应用于参数。

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)
  }
}

最新更新