Scala 作为一门函数式编程语言,对习惯了指令式编程语言的同学来说,会不大习惯,这里除了思维方式之外,还有语法层面的,比如 underscore(下划线)就会出现在多种场合,令初学者相当疑惑,今天就来总结下 Scala 中下划线的用法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
1、存在性类型:Existential types
def foo(l: List[Option[_]]) = ...
 
2、高阶类型参数:Higher kinded type parameters
case class A[K[_],T](a: K[T])
 
3、临时变量:Ignored variables
val _ = 5
 
4、临时参数:Ignored parameters
List(123) foreach { _ => println("Hi") }
 
5、通配模式:Wildcard patterns
Some(5match case Some(_=> println("Yes") }
val (a, _= (12)
for (_ <- 1 to 10)
 
6、通配导入:Wildcard imports
import java.util._
 
7、隐藏导入:Hiding imports
import java.util.{ArrayList =__}
 
8、连接字母和标点符号:Joining letters to punctuation
def bang_!(x: Int) = 5
 
9、占位符语法:Placeholder syntax
List(123) map (_ 2)
_ _   
 
10、偏应用函数:Partially applied functions
List(123) foreach println _
 
11、初始化默认值:default value
var i: Int = _
 
12、访问元组:tuple getters
t._2 
 
13、参数序列:parameters Sequence 
_*作为一个整体,告诉编译器你希望将某个参数当作参数序列处理!例如val = sum(1 to 5:_*)就是将1 to 5当作参数序列处理。

这里需要注意的是,以下两种写法实现的是完全不一样的功能:

1
2
3
foo _               // Eta expansion of method into method value
 
foo(_)              // Partial function application

Example showing why foo(_) and foo _ are different:

1
2
3
4
5
6
7
8
trait PlaceholderExample {
  def process[A](f: => Unit)
 
  val set: Set[_ => Unit]
 
  set.foreach(process _// Error 
  set.foreach(process(_)) // No Error
}

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/

浅谈 Scala 中下划线的用途的更多相关文章

  1. 转载:浅谈 Scala 中下划线的用途

    Scala 作为一门函数式编程语言,对习惯了指令式编程语言的同学来说,会不大习惯,这里除了思维方式之外,还有语法层面的,比如 underscore(下划线)就会出现在多种场合,令初学者相当疑惑,今天就 ...

  2. Scala 中下划线的用途

    转载自:https://my.oschina.net/leejun2005/blog/405305 Scala 作为一门函数式编程语言,对习惯了指令式编程语言的同学来说,会不大习惯,这里除了思维方式之 ...

  3. Scala 中下划线的用法

    1.存在性类型:Existential types def foo(l: List[Option[_]]) = ... 2.高阶类型参数:Higher kinded type parametersca ...

  4. 浅谈html5某些新元素的用途

    大家都知道html是一种前端网页语言,从出现到现在已经经历了很多的版本了,但是随着html的不断发展,现在的html5已经不再是单一的前端页面语言了,html,javascript,css不再单纯的只 ...

  5. Scala中下划线的总结

    1. 方法转化为函数 2. 集合中的每一个元素 3. 获取元组Tuple中的元素 4. 模式匹配 5. 队列 6. 导包引入的时候 7. 初始化变量 引用自:https://blog.csdn.net ...

  6. 浅谈Android编码规范及命名规范

    前言: 目前工作负责两个医疗APP项目的开发,同时使用LeanCloud进行云端配合开发,完全单挑. 现大框架已经完成,正在进行细节模块上的开发 抽空总结一下Android项目的开发规范:1.编码规范 ...

  7. Android安全开发之浅谈密钥硬编码

    Android安全开发之浅谈密钥硬编码 作者:伊樵.呆狐@阿里聚安全 1 简介 在阿里聚安全的漏洞扫描器中和人工APP安全审计中,经常发现有开发者将密钥硬编码在Java代码.文件中,这样做会引起很大风 ...

  8. 浅谈对Spring Framework的认识

    Spring Framework,作为一个应用框架,官方的介绍如下: The Spring Framework provides a comprehensive programming and con ...

  9. 浅谈struts2之chain

    转自:http://blog.csdn.net/randomnet/article/details/8656759 前一段时间,有关chain的机制着实困绕了许久.尽管网上有许多关于chain的解说, ...

随机推荐

  1. 解决Ubuntu下内存不足---作为Slave的虚拟机

    1)在虚拟机上安装了Ubuntu桌面版作为DataNode,由于物理机内存的限制只是分了1G的内存给虚拟机,使用bin/start-all.sh启动了hadoop之后,Slave的资源使用情况如下图所 ...

  2. iOS应用间的跳转和传值

    在第一个应用程序中info.plist设置 URL Identifier: 该字符串是你自定义的 URL scheme 的名字 注意: URL Schemes 是一个数组,允许应用定义多个 URL s ...

  3. POJ 2014

    #include <iostream> using namespace std; int main() { //freopen("acm.acm","r&qu ...

  4. .NET Framework 框架简述01

    NET技术可以以规范和实现两部分来划分.   规范:   公共语言架构(Common Language Infrastructure, CLI),主要包括 1.通用类型系统(Common Type S ...

  5. C# 实现抓取网站页面内容

    抓取新浪网的新闻栏目,如图所示: 使用 谷歌浏览器的查看源代码: 通过分析得知,我们所要找的内容在以下两个标签之间: <!-- publish_helper name='要闻-新闻' p_id= ...

  6. sql只修改第一二行数据

    update t_table set colname=*  where a=1 order by id desc limit 1,2

  7. 关于WII光枪定位的设计(转)

    方法1. 简单1 LED方法 这是一个很忽悠的方法,把LED看成是屏幕中心,把光枪摄像头的视野范围看作是屏幕范围. 假设WII枪头摄像头的数据范围为[0,1024]*[0,768],显示器屏幕分辨率为 ...

  8. 如何在solution中添加一个test case

    在solution Explorer中右键点击需要添加的folder,选择Add-New Item.也可以选择使用相应Unit Test之类的.Generic Test一般用于创建manual cas ...

  9. ThreadLocal的几种误区

    最近由于需要用到ThreadLocal,在网上搜索了一些相关资料,发现对ThreadLocal经常会有下面几种误解 一.ThreadLocal是java线程的一个实现       ThreadLoca ...

  10. CodeForces485B——Valuable Resources(水题)

    Valuable Resources Many computer strategy games require building cities, recruiting army, conquering ...