我正在学习 Scala 应用和高阶函数。我有这个编码,但为什么编译器给我一个错误:“缺少参数类型”,如何解决?
import scala.collection.mutable.ListBuffer
object MyArr {
var mList1 = ListBuffer[Int]()
def filter(p: Int => Boolean): List[Int] = {
val mList = List[Int]()
for (x <- mList1) {
if (p(x)) x :: mList
}
mList
}
def apply(x: Array[Int]) = {
for (y <- x) mList1 += y
}
}
def isEven(x: Int): Boolean = {
x % 2 == 0
}
var mCustomArr = MyArr(Array(1, 2, 3, 4))
mCustomArr.filter(x => isEven(x)).foreach(println)
如果 apply 方法只接受一个参数并将其添加到 mList1 ,它将起作用。为什么 ?
谢谢
如果您在apply()
定义中添加了返回类型,编译器会准确指出错误在哪里。
def apply(x: Array[Int]): ListBuffer[Int] = {
for (y <- x) mList1 += y
mList1
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句