簡體   English   中英

Scala:映射字符串時錯誤的類型推斷?

[英]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

translatemap的第二次調用是映射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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM