Scala 中下划线的用途
转载自:https://my.oschina.net/leejun2005/blog/405305
Scala 作为一门函数式编程语言,对习惯了指令式编程语言的同学来说,会不大习惯,这里除了思维方式之外,还有语法层面的,比如 underscore(下划线)就会出现在多种场合,令初学者相当疑惑,今天就来总结下 Scala 中下划线的用法。
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(1, 2, 3) foreach { _ => println("Hi") }
5、通配模式:Wildcard patterns
Some(5) match { case Some(_) => println("Yes") }
match {
case List(1,_,_) => " a list with three element and the first element is 1"
case List(_*) => " a list with zero or more elements "
case Map[_,_] => " matches a map with any key type and any value type "
case _ =>
}
val (a, _) = (1, 2)
for (_ <- 1 to 10)
6、通配导入:Wildcard imports
import java.util._
7、隐藏导入:Hiding imports
// Imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }
// Imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }
8、连接字母和标点符号:Joining letters to punctuation
def bang_!(x: Int) = 5
9、占位符语法:Placeholder syntax
List(1, 2, 3) map (_ + 2)
_ + _ ( (_: Int) + (_: Int) )(2,3)
val nums = List(1,2,3,4,5,6,7,8,9,10)
nums map (_ + 2)
nums sortWith(_>_)
nums filter (_ % 2 == 0)
nums reduceLeft(_+_)
nums reduce (_ + _)
nums reduceLeft(_ max _)
nums.exists(_ > 5)
nums.takeWhile(_ < 8)
10、偏应用函数:Partially applied functions
def fun = { // Some code
}
val funLike = fun _
List(1, 2, 3) foreach println _
1 to 5 map (10 * _)
//List("foo", "bar", "baz").map(_.toUpperCase())
List("foo", "bar", "baz").map(n => n.toUpperCase())
11、初始化默认值:default value
var i: Int = _
12、作为参数名:
//访问map
var m3 = Map((1,100), (2,200))
for(e<-m3) println(e._1 + ": " + e._2)
m3 filter (e=>e._1>1)
m3 filterKeys (_>1)
m3.map(e=>(e._1*10, e._2))
m3 map (e=>e._2)
//访问元组:tuple getters
(1,2)._2
13、参数序列:parameters Sequence _*作为一个整体,告诉编译器你希望将某个参数当作参数序列处理。例如val s = sum(1 to 5:_*)就是将1 to 5当作参数序列处理。
//Range转换为List
List(1 to 5:_*)
//Range转换为Vector
Vector(1 to 5: _*)
//可变参数中
def capitalizeAll(args: String*) = { args.map { arg => arg.capitalize }
}
val arr = Array("what's", "up", "doc?")
capitalizeAll(arr: _*)
这里需要注意的是,以下两种写法实现的是完全不一样的功能:
foo _ // Eta expansion of method into method value
foo(_) // Partial function application
Example showing why foo(_) and foo _ are different:
trait PlaceholderExample { def process[A](f: A => 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)
[3] Scala中的下划线到底有多少种应用场景?
http://www.zhihu.com/question/21622725
[4] Strange type mismatch when using member access instead of extractor
[5] Scala简明教程
http://colobu.com/2015/01/14/Scala-Quick-Start-for-Java-Programmers/
Scala 中下划线的用途的更多相关文章
- 浅谈 Scala 中下划线的用途
Scala 作为一门函数式编程语言,对习惯了指令式编程语言的同学来说,会不大习惯,这里除了思维方式之外,还有语法层面的,比如 underscore(下划线)就会出现在多种场合,令初学者相当疑惑,今天就 ...
- 转载:浅谈 Scala 中下划线的用途
Scala 作为一门函数式编程语言,对习惯了指令式编程语言的同学来说,会不大习惯,这里除了思维方式之外,还有语法层面的,比如 underscore(下划线)就会出现在多种场合,令初学者相当疑惑,今天就 ...
- Scala 中下划线的用法
1.存在性类型:Existential types def foo(l: List[Option[_]]) = ... 2.高阶类型参数:Higher kinded type parametersca ...
- Scala中下划线的总结
1. 方法转化为函数 2. 集合中的每一个元素 3. 获取元组Tuple中的元素 4. 模式匹配 5. 队列 6. 导包引入的时候 7. 初始化变量 引用自:https://blog.csdn.net ...
- Python中下划线---完全解读(转)
Python中下划线---完全解读 Python 用下划线作为变量前缀和后缀指定特殊变量 _xxx 不能用’from module import *’导入 __xxx__ 系统定义名字 __xxx ...
- Python中下划线的使用方法
本文将讨论Python中下划线(_)字符的使用方法.我们将会看到,正如Python中的很多事情,下划线的不同用法大多数(并非所有)只是常用惯例而已. 单下划线(_) 通常情况下,会在以下3种场景中使用 ...
- python中下划线
引用:https://blog.csdn.net/tcx1992/article/details/80105645?from=timeline Python中下划线的5种含义 class A(obje ...
- python中下划线_的用途
Python 用下划线作为变量前缀和后缀指定特殊变量. _xxx 不能用'from module import *'导入 __xxx__ 系统定义名字 __xxx 类中的私有变量 ...
- scala下划线
作为函数的参数 一个匿名的函数传递给一个方法或者函数的时候,scala会尽量推断出参数类型.例如一个完整的匿名函数作为参数可以写为 scala> def compute(f: (Double)= ...
随机推荐
- Centos7 Docker 多主机 容器互连--基于OVS
来一张自己画的图,mark:2016年6月27日17:09:14 自己理解,如有错误 多谢指教. centos7, 部署OVS和docker.以及基于centos6.8的ssh images 命令. ...
- Hadoop 2.6.0 Namenode HA,ResourceManager HA
先启动所有的zookeeper zkServer.sh start 在所有节点上启动JournalNode: sbin/hadoop-daemon.sh start journalnode 格式化第一 ...
- 使用 ServiceStack 构建跨平台 Web 服务
本文主要来自MSDN杂志<Building Cross-Platform Web Services with ServiceStack>,Windows Communication Fou ...
- .NET Core中遇到奇怪的线程死锁问题:内存与线程数不停地增长
一个 asp.net core 站点,之前运行在Linux 服务器上,运行一段时间后有时站点会挂掉,在日志中记录很多“EMFILE too many open files”的错误: Microsoft ...
- RCF进程间通信Demo程序
在上一篇文章RPC通信框架--RCF介绍中,介绍了RCF的优点,本篇文章从头开始演示如何用RCF编写一个跨进程通信的Demo程序. 将RCF编译为静态库 从官网下载到的源码中包含一个RCF的项目,但是 ...
- 《精通正则表达式》笔记 --- “验证”Email格式
写一个正则表达式的三个步骤: 理解需求并找出你需要验证的数据的特征: 写一个还可以用的正则表达式: 看看能不能达到你的目的,同时想想会不会匹配到一些不想要的数据: [可选]性能优化 我觉得写一个正则表 ...
- 用python实现的百度音乐下载器-python-pyqt-改进版
之前写过一个用python实现的百度新歌榜.热歌榜下载器的博文,实现了百度新歌.热门歌曲的爬取与下载.但那个采用的是单线程,网络状况一般的情况下,扫描前100首歌的时间大概得到40来秒.而且用Pyqt ...
- Ubuntu 16 安装ElasticSearch
首先安装Java,参见博客:http://www.cnblogs.com/1zhk/p/6056406.html 下载ElasticSearch安装包 curl -L -O https://artif ...
- [oracle]逗号(或分号等)间隔的列,按这一列劈分后转多行
今天遇到个需求,要匹配两个表, 但是关联的字段,在另一个表中是放在一个字段中用分号分割的 怎么全部匹配呢? 后来在网上搜到了, 记录下 SELECT cp.ES_EXTNUMBER, cp.ES_AG ...
- 关闭form上chrome的autofill
Chrome的autofill会自动找到form中的type=password的元素,然后把这个元素前面的元素当做是用户名,它不在乎这个元素叫什么名字.这样又是注册又是登录,你会发现它自作聪明的aut ...