[英]Scala: wrong type inference when mapping Strings?
我正在嘗試在Scala中編譯簡單的helloworld,並收到錯誤消息“ scala:value capitalize不是Char的成員”為什么編譯器認為newW是Char?
val dict = Map(
"hello" -> "olleh",
"world" -> "dlrow"
)
def translate(input: String): String = {
input.split( """\s+""").map(w => dict.getOrElse(w.toLowerCase, w).map(newW =>
(if (w(0).isUpper) newW.capitalize else newW))
).mkString(" ")
}
這是正在發生的事情:
input // is a string
.split( """\s+""") // is an Array[String]
.map(w => // w is a String, for each String in the Array[String]
dict.getOrElse(w.toLowerCase, w) // is a String (returned by dict.getOrElse)
.map(newW => // is a Char, for each Char in the String returned by dict.getOrElse
translate
對map
的第二次調用是映射dict.getOrElse(...)
返回的值,該值的類型為String
,可以將其隱式視為Iterable[Char]
。 因此,編譯器正確地推斷newW
屬於Char
類型,並且在您嘗試對其調用capitalize
時抱怨。 您可能正在尋找一些類似的東西
def translate(input: String): String = {
input.split( """\s+""").map(w => {
val newW = dict.getOrElse(w.toLowerCase, w)
(if (w(0).isUpper) newW.capitalize else newW)
}).mkString(" ")
}
更新:順便說一句,如果input
為空字符串,這將在運行時失敗-需要至少檢查一次安全性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.