我们都知道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函数传递进去
我也是今天刚懂的,记录一下,不知道理解的对错
本文详细介绍了Scala中字符串foreach方法的三种不同调用方式及其背后的原理。第一种为直接定义匿名函数并传入;第二种利用Scala语法特性简化函数参数;第三种则直接传递预定义函数。
1883

被折叠的 条评论
为什么被折叠?



