Scala中的占位符 _

来源:互联网 发布:win7的网络共享在哪里 编辑:程序博客网 时间:2024/05/02 02:02

         我们都知道scala的语法十分的简洁,有些语法简洁的让人找不到北。话不多说,看看占位符 _





下面就解释下为什么:

         


override def foreach[U](f: Char => U): Unit

Applies a function f to all elements of this string.

Note: this method underlies the implementation of most other bulk operations. Subclasses should re-implement this method if a more efficient implementation exists.


这是鼠标悬停在 foreach 看到的解释,foreach 接受一个函数参数,该函数传入类型Char ,返回空。这个应该能懂的!


     "hello".foreach((x:Char)=>println(x))   这种写法是在foreach里面构造一个匿名函数



      "hello".foreach(println(_))     这种写法本质上也是在构造一个匿名函数,Scala语法规定  匿名函数,如果 =》右边          只出现一次函数参数,切记只出现一次,(x:Char)就可以略去



      "hello".foreach(println)   这种写法相信大家都懂,就是把println函数传递进去




我也是今天刚懂的,记录一下,不知道理解的对错








1 0
原创粉丝点击