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)
当然,由于类型擦除不会起作用,但模仿上述内容的最佳方法是什么?
答案 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)
}
}