简体   繁体   English

匿名函数的scala列表

[英]scala list of anonymous functions

Like to create a list of function literals and (a) avoid pre-defining them and (b) use shorthand syntax. 类似于创建函数文字列表,并且(a)避免预定义它们,并且(b)使用简写语法。 Failing at the moment. 此刻失败。

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.

Please clarify, do you know types of your functions in advance? 请澄清一下,您是否事先知道您的功能类型?

If yes, then you can explicitly specify type of your list: 如果是,那么您可以显式指定列表的类型:

@ List[Int=>Int](x => x + 1, x => x + 2)

res20: List[Int => Int] = List(<function1>, <function1>)

Or even shorter: 甚至更短:

@ List[Int=>Int](_ + 1, _ + 2)

res21: List[Int => Int] = List(<function1>, <function1>)

If you want List type to be inferred, try following syntax: 如果要推断列表类型,请尝试以下语法:

@ List({ x: Int => x + 1}, { x: Int => x + 2 })
res22: List[Int => Int] = List(<function1>, <function1>)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM