[英]Scala placeholder syntax for anonymous function
我有一個類型為Array的val numSeq
scala> val numSeq=Array(3.1415,2.71828,9.8)
numSeq: Array[Double] = Array(3.1415, 2.71828, 9.8)
現在想要使用占位符語法將numSeq
每個元素轉換為Int
並將其打印出來。 毫無疑問,以下失敗:
scala> numSeq foreach (println (_.toInt))
<console>:13: error: missing parameter type for expanded function ((x$1: <error>) => x$1.toInt)
numSeq foreach (println (_.toInt))
但令我驚訝的是以下陳述是有道理的:
scala> numSeq foreach (Console println _.toInt)
3
2
9
但為什么它沒關系,只添加了前綴Console
?
這是因為詞匯范圍以及它們如何被scalac識別:
_.toInt
是一個函數 println(_.toInt)
:要打印一個函數,輸入類型不解析 Console.println(_.toInt)
:同樣,打印一個函數 Console println _.toInt
實際上與:( (x => Console println x.toInt)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.