转载自: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)

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 中下划线的用途

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

  3. Scala 中下划线的用法

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

  4. Scala中下划线的总结

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

  5. Python中下划线---完全解读(转)

      Python中下划线---完全解读 Python 用下划线作为变量前缀和后缀指定特殊变量 _xxx 不能用’from module import *’导入 __xxx__ 系统定义名字 __xxx ...

  6. Python中下划线的使用方法

    本文将讨论Python中下划线(_)字符的使用方法.我们将会看到,正如Python中的很多事情,下划线的不同用法大多数(并非所有)只是常用惯例而已. 单下划线(_) 通常情况下,会在以下3种场景中使用 ...

  7. python中下划线

    引用:https://blog.csdn.net/tcx1992/article/details/80105645?from=timeline Python中下划线的5种含义 class A(obje ...

  8. python中下划线_的用途

    Python 用下划线作为变量前缀和后缀指定特殊变量. _xxx       不能用'from module import *'导入 __xxx__  系统定义名字 __xxx     类中的私有变量 ...

  9. scala下划线

    作为函数的参数 一个匿名的函数传递给一个方法或者函数的时候,scala会尽量推断出参数类型.例如一个完整的匿名函数作为参数可以写为 scala> def compute(f: (Double)= ...

随机推荐

  1. C++基础_总结

    (1)多态性都有哪些?(静态和动态,然后分别叙述了一下虚函数和函数重载) 多态分为两种:静态和动态.静态主要包括函数重载和模板:动态主要是依靠虚函数实现的. 静态联编:重载函数不加virtual关键字 ...

  2. 微信支付:JSAPI支付一直提示URL未注册

    今天意外碰上了这个问题,想想微信的坑真多…… 解决办法: 首先要看微信公众号里的 支付授权目录 是否已正确填写,还要验证 url大小写 必须相同 其次查看一下自己请求的地址是否与上面填写的是否一样!u ...

  3. CGI和ISAPI

    1) CGI概念CGI即通用网关接口(Common Gateway Interface),它是一段程序,运行在服务器上,提供同客户端HTML页面的交互,通俗的讲CGI就象是一座桥,把网页和WEB服务器 ...

  4. Your awesome titleHH

    Welcome to Jekyll! Your awesome titleHH About Blogging Like a Hacker Welcome to Jekyll! Jan 9, 2016 ...

  5. Web Api 与 Andriod 接口对接开发经验

    最近一直急着在负责弄Asp.Net Web Api 与 Andriod 接口开发的对接工作! 刚听说要用Asp.Net Web Api去跟 Andriod 那端做接口对接工作,自己也是第一次接触Web ...

  6. ABP理论学习之启动配置

    返回总目录 本篇目录 配置ABP 配置模块 为模块创建配置 为了在应用启动时配置ABP和模块,ABP提供了一个基础设施. 配置ABP 配置ABP是在模块的PreInitialize事件中完成的.下面的 ...

  7. HTML和CSS经典布局2

    如下图: 需求: 1. 如图 2. 可以从body标签开始. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xht ...

  8. kpvalidate开辟验证组件,通用Java Web请求服务器端数据验证组件

    小菜利用工作之余编写了一款Java小插件,主要是用来验证Web请求的数据,是在服务器端进行验证,不是简单的浏览器端验证. 小菜编写的仅仅是一款非常初级的组件而已,但小菜为它写了详细的说明文档. 简单介 ...

  9. 顶级的JavaScript框架、库、工具及其使用

    几乎每隔一个星期,就有一个新的 JavaScript 库席卷网络社区!Web 社区日益活跃.多样,并在多个领域快速成长.想要研究每一个重要的 JavaScript 框架和库,是个不可能完成的任务.接下 ...

  10. 2016苹果春季发布会 iPhone SE发布

    配置如下 主屏尺寸:4英寸 主屏分辨率:1336x640像素 后置摄像头:1200万像素 前置摄像头:120万像素 电池容量:1624mAh 核心数:双核 操作系统:iOS 9 核心数:双核 CPU: ...