所以对于一个非常小的公式解释者,有人问我打码 - 高尔夫,我想做点什么
val ops = Map("plus" -> + , "minus"-> -, "times"-> *, "div" -> / )
Run Code Online (Sandbox Code Playgroud)
允许关键字与其描述的功能之间的快速转换.这个语法不仅没有解析,也没有我试过(_ + _
,_:Int.+_
)解析的其他简写语法.有没有办法把它作为一种功能简写,或者我注定要完全写出lambdas,毁了我的高尔夫球得分.
编辑:问题只是整数.据我所知,超载会使这更加困难.
不确定如何通过定义附加功能来影响您的分数.您可以使用以下内容提升运算符:
def lift(f:(Int,Int)=>Int) = f
val ops = Map("plus" -> lift(_+_), "minus" -> lift(_-_), "times"-> lift(_*_), "div" -> lift(_/_))
Run Code Online (Sandbox Code Playgroud)
如果你想刮一些字符:
def ?(f:(Int,Int)=>Int) = f
val ops = Map("plus" -> ?(_+_), "minus" -> ?(_-_), "times"-> ?(_*_), "div" -> ?(_/_))
Run Code Online (Sandbox Code Playgroud)
并且作为om-nom-nom评论,这个明确的提升可以由编译器完成,同时提供类型签名以强制解除:
val ops: Map[String, (Int,Int) => Int] = Map("plus" -> (_+_), "minus" -> (_-_), "times"->(_*_), "div" -> (_/_))
Run Code Online (Sandbox Code Playgroud)