浅谈 Scala 中下划线的用途
2015-06-02 13:51
225 查看
Scala 作为一门函数式编程语言,对习惯了指令式编程语言的同学来说,会不大习惯,这里除了思维方式之外,还有语法层面的,比如 underscore(下划线)就会出现在多种场合,令初学者相当疑惑,今天就来总结下 Scala 中下划线的用法。
?
这里需要注意的是,以下两种写法实现的是完全不一样的功能:
?
Example showing why foo(_) and foo _ are different:
?
In the first case, process _ represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for A that will give the type (_ => Unit) => ? (Existential _ is not a type).
In the second case, process(_) is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach expects, and _ => Unit is a type (whereas just plain _ isn't), so it can be substituted and inferred.
This may well be the trickiest gotcha in Scala I have ever encountered.
Refer:
[1] What are all the uses of an underscore in Scala?
http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala
[2] Scala punctuation (AKA symbols and operators)
http://stackoverflow.com/questions/7888944/scala-punctuation-aka-symbols-and-operators/7890032#7890032
[3] Scala中的下划线到底有多少种应用场景?
http://www.zhihu.com/question/21622725
[4] Strange type mismatch when using member access instead of extractor
http://stackoverflow.com/questions/9610736/strange-type-mismatch-when-using-member-access-instead-of-extractor/9610961
[5] Scala简明教程
http://colobu.com/2015/01/14/Scala-Quick-Start-for-Java-Programmers/
?
?
?
In the second case, process(_) is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach expects, and _ => Unit is a type (whereas just plain _ isn't), so it can be substituted and inferred.
This may well be the trickiest gotcha in Scala I have ever encountered.
Refer:
[1] What are all the uses of an underscore in Scala?
http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala
[2] Scala punctuation (AKA symbols and operators)
http://stackoverflow.com/questions/7888944/scala-punctuation-aka-symbols-and-operators/7890032#7890032
[3] Scala中的下划线到底有多少种应用场景?
http://www.zhihu.com/question/21622725
[4] Strange type mismatch when using member access instead of extractor
http://stackoverflow.com/questions/9610736/strange-type-mismatch-when-using-member-access-instead-of-extractor/9610961
[5] Scala简明教程
http://colobu.com/2015/01/14/Scala-Quick-Start-for-Java-Programmers/
相关文章推荐
- pig-csm 7.9修改记录
- 获取本地图片并显示
- Android应用Context详解及源码解析
- MVC模式
- JavaScript中字符串截取函数slice()、substring()、substr()
- 第四节---nginx+php
- maven如何修改本地仓库与中央仓库
- Java中的final详解以及用途实战
- 朴素贝叶斯分类
- 线程安全
- accordion-折叠面板
- Node.js Web模块
- UML类图之类与类的关系
- python启动线程的3中方案
- Advanced Bash-Shell Guide(Version 10) 学习笔记三
- Android BLE 蓝牙低功耗教程,中央BluetoothGatt和周边BluetoothGattServer的实现
- Spark特性分析
- 九度OJ-题目1512:用两个栈实现队列
- HTML img标签之onAbort、onError、onLoad事件与问题
- 中文分词-lucene 第一个版本