scala - scala map 的花括号和括号
问题描述
Array(7,8,9) map (x:Int=>x+1) //1).error, identifier expected but integer literal found.
Array(7,8,9) map {x:Int=>x+1} //2) correct
Array(7,8,9) map ((x:Int)=>x+1) //3) correct
Array(7,8,9) map (x=>x+1) //4 correct
Array(7,8,9) map {x=>x+1} //5 correct
Array(7,8,9) map x=>x+1 //6 error
我会询问上述情况,为什么有些工作,而另一些则没有如评论所示
解决方案
为了:
Array(7,8,9) map {x:Int=>x+1} //2) correct
Array(7,8,9) map {x=>x+1} //5 correct
在单个无类型形式参数的情况下,(x) => e 可以缩写为 x => e。如果带有单个类型参数的匿名函数 (x: T) => e 作为块的结果表达式出现,则可以缩写为 x: T => e。
对于 type Int
,Scala可以在这个上下文下推断这个Type 。
推荐阅读
- c# - 抓住物体时角色无法控制地移动
- c# - What is (! is)?
- c# - 从单个列表c#中查找所有可能的序列列表
- burp - burpsuite 的 Sql 注入问题
- cognos - Cognos 在启动时会向通知默认发件人发送一封测试电子邮件。如何停止或更改此电子邮件?
- python-3.x - 使用 NLP 模型查找该语句中存在的特定对象
- autodesk-forge - 以编程方式设置主题颜色时颜色不会改变
- css - 使用 Css 模块 @import @value 创建 React 应用程序
- linux - 如何操作 Bash 中的特定输出(正常运行时间)?
- regex - 如何识别字符串中的两个或三个模式并删除从第一个标识到最后一个标识的所有元素?