首页 文章

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

提问于
浏览
1

我正在尝试在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(" ")
}

2 回答

  • 3

    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(" ")
    }
    

    Update: 顺便说一句,如果 input 是一个空字符串,它将在运行时失败 - 它至少需要再检查一次安全性 .

  • 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
    

相关问题