【发布时间】:2016-08-11 10:23:40
【问题描述】:
myFunc 的第二个参数是一个具有复杂参数的函数:
def myFunc(list : List[String],
combine: (Map[String, ListBuffer[String]], String, String) => Unit) = {
// body of myFunc is just a stub and doesn't matter
val x = Map[String, ListBuffer[String]]()
list.foreach ((e:String) => {
val spl = e.split(" ")
combine(x, spl(0), spl(1))
})
x
}
我需要将第二个参数传递给myFunc,因此它可以用于各种类型的A, B,而不是特定的String, ListBuffer[String]。
def myFunc(list : List[A], combine: (Map[A, B], A, A) => Unit) = {
val x = Map[A, B]()
list.foreach(e => {
combine(x, e)
})
}
如何声明和调用这样的构造?
【问题讨论】:
-
需要指定A和B是类型参数,像这样:
def myFunc[A, B](list: List[A], combine: (Map[A, B], A, A) => Unit)
标签: scala function generics lambda