Scala方法形參中傳入函式作為引數
阿新 • • 發佈:2021-01-14
在Scala中可以將函式作為引數傳遞到另一個方法中,程式碼如下:
object FunctionTest {
def main(args: Array[String]): Unit = {
test(plus)
}
def test(fun: => Unit): Unit = {
println("this is test run")
fun
}
def plus() = {
println("this is plus run")
}
}
執行結果:
this is test run
this is plus run
那麼 萬一這個傳入的函式自己本身也有形參怎麼辦呢?
object FunctionTest { def main(args: Array[String]): Unit = { test(plus, 23) } def test(fun: Int => Unit, num: Int): Unit = { println("this is test run") fun(num) } def plus(num: Int) = { println("this is plus run" + num) } }
執行結果:
this is test run
this is plus run23
還可以寫的更簡潔,類似java的匿名內部類,我願稱之為匿名函式:
object FunctionTest { def main(args: Array[String]): Unit = { test(num=>{ println("this is plus run" + num) }, 23) } def test(fun: Int => Unit, num: Int): Unit = { println("this is test run") fun(num) } }
執行結果同上。
看到這個匿名函式是不是有點像java中的forEach的寫法:
list.forEach(s -> testlist.add(s.getName()));
除了這個還有JDK1.8中新增的stream操作:
list.stream().map(d -> d.getName()).collect(Collectors.toList())
其實JDK1.8中的stream操作就是從scala借鑑來的。