List(1, 2, 3).collect { x =>
val dummy =()
x match { case _ => x }
}
結果
<console>:9: error: missing parameter type
List(1, 2, 3).collect { x =>
但這種看似相同的片段按預期工作:
List(1, 2, 3).collect { x =>
x match { case _ => x }
}
這是真的該collect
需要PartialFunction
,但我看到這一點的方式是,如果{ x => x match { ... } }
是PartialFunction
(它必須歸因於編譯器中的特殊情況,因爲它看起來就像是一個正常函數throws MatchError
),那麼{ x => smth(); x match { ... } }
也應該是PartialFunction
。 (編輯:我不知道,甚至第一案被推斷爲一個PartialFunction
)
的值,以及爲什麼你需要平穩()?順便說一句,你可以看看這篇[關於Scala中的部分函數的文章](http://www.scala-sbt.org/0.13.1/docs/Getting-Started/Library-Dependencies.html#resolvers)。 –
其實我需要做'smth - > x match {...}'這樣我就不必重複'match'的每個case中構造'smth'了;或者,我可以把它放在'val'中並在'case'中重複使用,但結果相同; (但文章是關於SBT的;你的剪貼板對你的玩弄技巧:)) –
不客氣:) 我不知道你的用例到底是什麼,但你可以嘗試像這樣:list.map( x => smth(x))。collect。 E.g. (list =「1」,「2」,「33」) list.map(elem => elem.toInt).collect(_ match {case x:Int if x> 2 => x}) 這:a)將每個字符串轉換爲int(您的smth()函數),b)收集> 2的整數。 –