鉴于以下情况
abstract class Animal {/***/}
class Dog(s : String) extends Animal {/***/}
class Cat(s :String) extends Animal {/***/}
class C() {
val animal: Animal = new Dog(name)
private def name = "name for animal that C knows how to calculate"
}
如何向C提供Animal实例,而不是创建它的C?
可以执行类似
的操作class B(f : String => Animal) {
val animal: Animal = f(name)
private def name = "name for animal that B knows how to calculate"
}
然后允许我
val bWithDog = new B((name: String) => new Dog(name))
val bWithCat = new B((name: String) => new Cat(name))
这是我的目标 但这是一个干净的解决方案吗? 或者将Animal提供给C是没有意义的,因为只有C知道如何计算它的名字?
答案 0 :(得分:0)
class C(val animal: Animal) {
private def name = "name for animal that C knows how to calculate"
}
new C(new Dog("fiddo"))
构造函数参数有什么问题?