如何将方法作为参数传递并在Scala中返回for循环?

时间:2019-02-21 01:12:01

标签: java scala

我的代码的问题在于方法“ 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
    }
}
}

2 个答案:

答案 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)