简体   繁体   English

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

[英]Scala: wrong type inference when mapping Strings?

I'm trying to compile simple helloworld in Scala, and get error "scala: value capitalize is not a member of Char" Why does compiler think that newW is Char? 我正在尝试在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(" ")
}

Here's what's happening: 这是正在发生的事情:

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

The second call to map in translate is mapping across the value returned from dict.getOrElse(...) , whose type is String , which can be implicitly treated as an Iterable[Char] . translatemap的第二次调用是映射dict.getOrElse(...)返回的值,该值的类型为String ,可以将其隐式视为Iterable[Char] Thus, the compiler is correctly inferring that newW is of type Char and complaining when you try to call capitalize on it. 因此,编译器正确地推断newW属于Char类型,并且在您尝试对其调用capitalize时抱怨。 You're probably looking for something along the lines of 您可能正在寻找一些类似的东西

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: By the way, that will fail at runtime if input is an empty string - it needs at least one more check for safety. 更新:顺便说一句,如果input为空字符串,这将在运行时失败-需要至少检查一次安全性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM