喜欢创建函数文字列表,(a)避免预定义它们,(b)使用简写语法。目前失败。
def g = (x: Int) => x + 1 //pre-defined
def h = (x: Int) => x + 2
List(g,h) //succeeds
List( (x: Int) => x + 1, (x: Int) => x + 2) ) //fails
^';' expected but ')' found.
答案 0 :(得分:1)
请澄清,您是否提前知道您的职能类型?
如果是,那么您可以明确指定列表的类型:
@ List[Int=>Int](x => x + 1, x => x + 2)
res20: List[Int => Int] = List(<function1>, <function1>)
甚至更短:
@ List[Int=>Int](_ + 1, _ + 2)
res21: List[Int => Int] = List(<function1>, <function1>)
如果要推断列表类型,请尝试以下语法:
@ List({ x: Int => x + 1}, { x: Int => x + 2 })
res22: List[Int => Int] = List(<function1>, <function1>)