转载:浅谈scala中下划线的用途

author author     2022-08-22     737

关键词:

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())

******·····用于将方法转换成函数,比如val f=sqrt _,以后直接调用f(250)就能求平方根了

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/

 


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

scala中下划线(代码片段)

替换java等价语法导入通配符//Javaimportjava.util.*;//Scalaimportjava.util._类成员默认值Java中类成员可以不赋初始值,编译器会自动帮你设置一个合适的初始值:classFoo//String类型的默认值为nullStrings;而在Scala中必须要显式指定࿰... 查看详情

scala中下划线与星号_*(代码片段)

1.变长参数defsum(args:Int*):Unit=println("sum:",args.length,args.sum)defmain(args:Array[String]):Unit=sum(1to5:_*)//变长参数必须加:_*输出:(sum:,5,15)2.变量声明中的模式defmain(args:Array[String]):Unit=valarr=Array(1,2,3,4,5)valArray(f,s,_*)=arr//把arr中的第一个和第二... 查看详情

[repost]python中下划线的5种含义

转载自:Python中下划线的5种含义PEP8—theStyleGuideforPythonCode 查看详情

[repost]python中下划线的5种含义

转载自:Python中下划线的5种含义PEP8—theStyleGuideforPythonCode 查看详情

scala中下划线_的用法总结(代码片段)

_(下划线)这个字符在Scala中似乎无处不在,到目前为止,它可能是Scala中使用最广泛的符号。使用场景清单:作为包引入的通配符作为元组索引的前缀.valnames:(String,String)=("lisi","zs")names._1names._2作为... 查看详情

标识符(代码片段)

...的中间和最后var++="123"println(++)var+-*/="123"println(+-*/)//scala中下划线有特殊用途,不能独立当成变量名使用 查看详情

如何更改按钮的边框颜色并更改editText中下划线的颜色?

】如何更改按钮的边框颜色并更改editText中下划线的颜色?【英文标题】:HowtochangethebordercolourforthebuttonandchangingthecolourforunderlineintheeditText?【发布时间】:2017-08-0302:15:31【问题描述】:我尝试了很多方法,但我的问题没有解决。... 查看详情

scalaeclipse代码出现下划线的问题解决

...上会出现标记,在代码下面会出现下划线。由于scala中下划线是经常出现的占位符,会和下划线重复,导致看代码特别难受。解决windows->preference->General->Editors->TextEditors->Annotations->ScalaIm 查看详情

如何改变clickablespan中下划线的颜色和样式

参考技术Atext-decoration:none默认。定义标准的文本。underline定义文本下的一条线。overline定义文本上的一条线。line-through定义穿过文本下的一条线。blink定义闪烁的文本。修饰的颜色由"color"属性设置本回答被提问者和网友采... 查看详情

scalaeclipse代码出现下划线的问题解决

...上会出现标记,在代码下面会出现下划线。由于scala中下划线是经常出现的占位符,会和下划线重复,导致看代码特别难受。解决windows->preference->General->Editors->TextEditors->Annotations->ScalaImplicit,或者不... 查看详情

如何改变clickablespan中下划线的颜色和样式

classMyClickableSpanextendsClickableSpanprivateArrayListtexts;publicMyClickableSpan(finalArrayListtexts)super();//TODOAuto-generatedconstructorstubthis.texts=texts;@OverridepublicvoidupdateDrawState(TextPaintds)//TODOAuto-generatedmethodstubsuper.updateDrawState(ds);ds.setUnderlineText(false);@Overr... 查看详情

如何改变clickablespan中下划线的颜色和样式

classMyClickableSpanextendsClickableSpanprivateArrayListtexts;publicMyClickableSpan(finalArrayListtexts)super();//TODOAuto-generatedconstructorstubthis.texts=texts;@OverridepublicvoidupdateDrawState(TextPaintds)//TODOAuto-generatedmethodstubsuper.updateDrawState(ds);ds.setUnderlineText(false);@Overr... 查看详情

mybatisplus查询列中下划线问题

Unknowncolumn'create_time'in'fieldlist'CreateTime数据库字段<resultcolumn="createtime"property="CreateTime"/>xml文件映射在不该数据库的前提下有没有方法解决你的这里使用的名字和数据库中的不一致吧,这个问题很常... 查看详情

为啥word文档中下划线会在按下tab键的时候自己打开,我一直在线。

在word文档里面如果用下划线的画好像不能达到这个效果你可以试试用word里面的绘图绘制横线这样横线的位置就可以调整了参考技术A不会啊,我尝试了一下在word中做下划线,也按tab键,但没有断开,你再试试。 参考技术B不会啊... 查看详情

Scala 符号的用途? [复制]

】Scala符号的用途?[复制]【英文标题】:PurposeofScala\'sSymbol?[duplicate]【发布时间】:2011-04-0300:47:34【问题描述】:可能重复:WhataresomeexampleusecasesforsymbolliteralsinScala?Symbol的用途是什么,为什么它值得一些特殊的literal语法e.G。\'Foo... 查看详情

c#wpf数据绑定header中下划线怎么显示出来啊?

第一步,先定义要绑定列表需要的集合数据的类publicclassFtpFileInformationprivateboolisDirectory;privatestringfilename;privatestringfiletime;privateintfilesize;publicboolIsDirectorygetreturnisDirectory;setisDirectory=value;this.OnPropertyChanged(IsDirectory.ToString());publicstring... 查看详情

Scala中的下划线[重复]

】Scala中的下划线[重复]【英文标题】:UnderscoreinScala[duplicate]【发布时间】:2021-07-0402:25:15【问题描述】:我在大学里学习了Scala1.5个月——我学到的是:集合、模式匹配、集合上的函数,但我的问题是:下划线到底是什么意思... 查看详情

转载etl浅谈

ETL是将业务系统的数据经过抽取、清洗转换之后加载到数据仓库的过程,目的是将企业中的分散、零乱、标准不统一的数据整合到一起,为企业的决策提供分析依据。 ETL是BI项目重要的一个环节。通常情况下,在BI项目中ETL... 查看详情