您的位置:首页 > 其它

Scala中的占位符 _

2017-01-15 19:50 134 查看
         我们都知道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函数传递进去

我也是今天刚懂的,记录一下,不知道理解的对错
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息