Scala:映射字符串时类型推断错误?
我正在尝试用Scala编译简单的helloworld, 并获取错误“scala:value capitalize不是Char的成员” 为什么编译器认为newW是CharScala:映射字符串时类型推断错误?,scala,type-inference,Scala,Type Inference,我正在尝试用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.getOrEl
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
下面是正在发生的事情:
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
类型,并在尝试调用大写时发出抱怨。你可能在寻找类似于
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
是一个空字符串,那么在运行时它将失败-它至少需要再检查一次安全性。在translate
中对map
的第二次调用是对从dict.getOrElse(…)
返回的值进行映射,该值的类型是string
,可以隐式地将其视为Iterable[Char]
。因此,编译器正确地推断出newW
属于Char
类型,并在尝试调用大写时发出抱怨。你可能在寻找类似于
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
是一个空字符串,那么在运行时它将失败-它需要至少再检查一次安全性。从技术上讲,string
不是List[Char]
,这与Haskell不同。我认为它们之间有一种隐含的转换。从技术上讲,String
不是List[Char]
,不像Haskell。我认为他们之间有一种隐含的转换。