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

  1. 1、存在性类型:Existential types
  2. def foo(l: List[Option[_]]) = ...
  3. 2、高阶类型参数:Higher kinded type parameters
  4. case class A[K[_],T](a: K[T])
  5. 3、临时变量:Ignored variables
  6. val _ = 5
  7. 4、临时参数:Ignored parameters
  8. List(1, 2, 3) foreach { _ => println("Hi") }
  9. 5、通配模式:Wildcard patterns
  10. Some(5) match { case Some(_) => println("Yes") }
  11. match {
  12.      case List(1,_,_) => " a list with three element and the first element is 1"
  13.      case List(_*)  => " a list with zero or more elements "
  14.      case Map[_,_] => " matches a map with any key type and any value type "
  15.      case _ =>
  16.  }
  17. val (a, _) = (1, 2)
  18. for (<- 1 to 10)
  19. 6、通配导入:Wildcard imports
  20. import java.util._
  21. 7、隐藏导入:Hiding imports
  22. // Imports all the members of the object Fun but renames Foo to Bar
  23. import com.test.Fun.{ Foo => Bar , _ }
  24. // Imports all the members except Foo. To exclude a member rename it to _
  25. import com.test.Fun.{ Foo => _ , _ }
  26. 8、连接字母和标点符号:Joining letters to punctuation
  27. def bang_!(x: Int) = 5
  28. 9、占位符语法:Placeholder syntax
  29. List(1, 2, 3) map (+ 2)
  30. + _   
  31. ( (_: Int) + (_: Int) )(2,3)
  32. val nums = List(1,2,3,4,5,6,7,8,9,10)
  33. nums map (+ 2)
  34. nums sortWith(_>_)
  35. nums filter (% 2 == 0)
  36. nums reduceLeft(_+_)
  37. nums reduce (+ _)
  38. nums reduceLeft(_ max _)
  39. nums.exists(> 5)
  40. nums.takeWhile(< 8)
  41. 10、偏应用函数:Partially applied functions
  42. def fun = {
  43.     // Some code
  44. }
  45. val funLike = fun _
  46. List(1, 2, 3) foreach println _
  47. 1 to 5 map (10 * _)
  48. //List("foo", "bar", "baz").map(_.toUpperCase())
  49. List("foo", "bar", "baz").map(=> n.toUpperCase())
  50. ******·····用于将方法转换成函数,比如val f=sqrt _,以后直接调用f(250)就能求平方根了
  51. 11、初始化默认值:default value
  52. var i: Int = _
  53. 12、作为参数名:
  54. //访问map
  55. var m3 = Map((1,100), (2,200))
  56. for(e<-m3) println(e._1 + ": " + e._2)
  57. m3 filter (e=>e._1>1)
  58. m3 filterKeys (_>1)
  59. m3.map(e=>(e._1*10, e._2))
  60. m3 map (e=>e._2)
  61. //访问元组:tuple getters
  62. (1,2)._2
  63. 13、参数序列:parameters Sequence 
  64. _*作为一个整体,告诉编译器你希望将某个参数当作参数序列处理。例如val s = sum(1 to 5:_*)就是将1 to 5当作参数序列处理。
  65. //Range转换为List
  66. List(1 to 5:_*)
  67. //Range转换为Vector
  68. Vector(1 to 5: _*)
  69. //可变参数中
  70. def capitalizeAll(args: String*) = {
  71.   args.map { arg =>
  72.     arg.capitalize
  73.   }
  74. }
  75. val arr = Array("what's", "up", "doc?")
  76. capitalizeAll(arr: _*)

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

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

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

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

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/

转载自https://my.oschina.NET/leejun2005/blog/405305

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

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

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

  2. Scala 中下划线的用途

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

  3. 转载-浅谈Ddos攻击攻击与防御

    EMail: jianxin#80sec.comSite: http://www.80sec.comDate: 2011-2-10From: http://www.80sec.com/ [ 目录 ]一 ...

  4. [转载]浅谈JavaScript函数重载

     原文地址:浅谈JavaScript函数重载 作者:ChessZhang 上个星期四下午,接到了网易的视频面试(前端实习生第二轮技术面试).面了一个多小时,自我感觉面试得很糟糕的,因为问到的很多问题都 ...

  5. <转载>浅谈C/C++的浮点数在内存中的存储方式

    C/C++浮点数在内存中的存储方式 任何数据在内存中都是以二进制的形式存储的,例如一个short型数据1156,其二进制表示形式为00000100 10000100.则在Intel CPU架构的系统中 ...

  6. 转载--浅谈spring4泛型依赖注入

    转载自某SDN-4O4NotFound Spring 4.0版本中更新了很多新功能,其中比较重要的一个就是对带泛型的Bean进行依赖注入的支持.Spring4的这个改动使得代码可以利用泛型进行进一步的 ...

  7. Scala 中下划线的用法

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

  8. (转载) 浅谈python编码处理

    最近业务中需要用 Python 写一些脚本.尽管脚本的交互只是命令行 + 日志输出,但是为了让界面友好些,我还是决定用中文输出日志信息. 很快,我就遇到了异常: UnicodeEncodeError: ...

  9. [转载]浅谈组策略设置IE受信任站点

    在企业中,通常会有一些业务系统,要求必须加入到客户端IE受信任站点,才能完全正常运行访问,在没有域的情况下,可能要通过管理员手动设置,或者通过其它网络推送方法来设置. 有了域之后,这项工作就可以很好的 ...

随机推荐

  1. 给力开源,.Net开源地址大收集

    一.基础类库: 1,项目名:Npoi 资源星级:★★★ (个人评的) 介绍:NPOI - 一个能帮助你直接读写office文件流的库 系统教程:http://www.cnblogs.com/tonyq ...

  2. 如何自动播放光盘、解决win7电脑不能播放光盘

    如何设置光盘自动播放.允许光盘自动运行呢? 在使用电脑光驱播放光盘文件的时候,经常出现的一个问题是,光驱不能自动播放光盘,但是打开光盘的文件手动操作没有任何问题,这给使用造成了很多麻烦.那么,如何让光 ...

  3. python3简单使用requests 用户代理,cookie池

    官方文档:http://docs.python-requests.org/en/master/ 参考文档:http://www.cnblogs.com/zhaof/p/6915127.html#und ...

  4. 用户人品预测大赛--getmax队--竞赛分享

     用户人品预测大赛--getmax队--竞赛分享  DataCastle运营 发表于 2016-3-24 14:49:32      533  0  0 答辩PPT  

  5. Spring.profiles多环境配置最佳实践

    转自:https://www.cnblogs.com/jason0529/p/6567373.html Spring的profiles机制,是应对多环境下面的一个解决方案,比较常见的是开发和测试环境的 ...

  6. AWK常用技巧

    1.1 介绍 awk其名称得自于它的创始人 Alfred Aho .Peter Weinberger 和 Brian Kernighan 姓氏的首个字母.实际上 AWK 的确拥有自己的语言: AWK ...

  7. 【机器学习算法-python实现】採样算法的简单实现

    1.背景     採样算法是机器学习中比較经常使用,也比較easy实现的(出去分层採样).经常使用的採样算法有下面几种(来自百度知道):     一.单纯随机抽样(simple random samp ...

  8. 未能找到temp\select2.cur的一部分

    环境 操作系统:win10 家庭普通版本 x64 账户类型:管理员 SuperMap:9D 打开自定义的应用程序时,会报错:未能找到路径"C:\Users\user\AppData\Loca ...

  9. Memcache及telnent命令具体解释

    1.启动Memcache 经常使用參数 memcached 1.4.3 -p <num>      设置port号(默认不设置为: 11211) -U <num>      U ...

  10. java 对一个字符串进行加减乘除的运算

    记录一个小程序,里面涉及到的JAVA知识点有:字符串扫描,list删除元素的方法,泛型的使用,JAVA中的/要注意的事项.有兴趣的可以看看 package com.demo; import java. ...