我的代码的问题在于方法“ makeSomeNoise”。我想将方法“ animals”传递给“ makeSomeNoise”,因为我想将动物列表作为参数传递,然后在输入中返回包含每个动物(类)的噪音的字符串列表。
abstract class Animal(name: String) {
def sound(): String
override def toString: Animal
}
class Cat(var name: String)
extends Animal(name)
{
override def sound() = {
"meow"
}
}
class Dog(var name: String)
extends Animal(name){
override def sound() = {
"woof"
}
}
object Park{
def animals() = {
val a =List(new Dog("Snoopy"), new Dog("Finn"), new Cat("Garfield"),new Cat("Morris"))
a
}
def makeSomeNoise(Park.animals()) = {
for (i<-animals){
val b = List() :+ i.sound
b
}
}
}
答案 0 :(得分:0)
可能您想将其设为默认参数,并使用map进行迭代,它将返回由Map结果定义的Type。
def makeSomeNoise(animals: List[Animal] = Park.animals()) = {
animals.map(animal => animal.sound)
}
答案 1 :(得分:0)
不确定为什么将def
用于更自然的val
值。
这能满足您的需求吗?
abstract class Animal(name: String) {
def sound(): String
override def toString = "Animal"
}
class Cat(var name: String) extends Animal(name) {
override def sound() = "meow"
}
class Dog(var name: String) extends Animal(name) {
override def sound() = "woof"
}
object Park{
def animals() =
List(new Dog("Snoopy"), new Dog("Finn"), new Cat("Garfield"),new Cat("Morris"))
def makeSomeNoise(lst :List[Animal]) :List[String] = lst.map(_.sound())
}
Park.makeSomeNoise(Park.animals())
//res0: List[String] = List(woof, woof, meow, meow)