Scala:映射字符串时错误的类型推断?

时间:2013-02-14 23:28:40

标签: scala type-inference

我正在尝试在Scala中编译简单的hello世界, 并获得错误“scala:value capitalize不是Char的成员” 为什么编译器认为newS是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(" ")
}

2 个答案:

答案 0 :(得分:3)

以下是发生的事情:

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

答案 1 :(得分:3)

map中对translate的第二次调用是从dict.getOrElse(...)返回的值的映射,其类型为String,可以隐含地视为{{1} }}。因此,编译器正确地推断出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(" ") } 是一个空字符串,那么在运行时会失败 - 它至少需要再检查一次。