斯卡拉:“隐式转换不适用”在一个简单的表达 [英] Scala: 'implicit conversions are not applicable' in a simple for expression
问题描述
类示例{
def对于(c <-s){
// ...
}
}
}
,forString(s:String)= {
,并且始终与信息失败:
错误:类型不匹配;
找到:Int
required:java.lang.Object
请注意,隐式转换不适用,因为它们是不明确的:
...
for(c< - s){
^
找到一个错误
我尝试将循环更改为几件事情,包括使用字符串的长度和使用硬编码的数字(仅用于测试),但无济于事。搜索网络并没有产生任何东西...
编辑:这个代码是我可以减少到最小的代码,而仍然屈服错误:
class示例{
def forString(s:String)= {
for(c < - s){
println(String.format(%03i,c.toInt))
}
}
}
错误与上面相同,并且在编译时发生。在解释器中运行得到相同的结果。 解决方案
不要使用原始的 String.format
方法。对隐式转换的 RichString
使用 .format
方法。它会为你装上原始的东西。即
jem @尊重:〜$ scala
欢迎来到Scala 2.8.0.final(Java HotSpot(TM) )客户端VM,Java 1.6.0_21)。
键入表达式让他们评估。
输入:help获取更多信息。
scala> class示例{
| def forString(s:String)= {
| for(c < - s){
| println(%03i.format(c.toInt))
| }
| }
| }
定义的类示例
scala> new Example().forString(9)
java.util.UnknownFormatConversionException:Conversion ='i'
更接近,但不完全。您可以尝试%03d
作为您的格式字符串。
阶> %03d.format(9.toInt)
res3:String = 009
I started out with Scala today, and I ran into an intriguing problem. I am running a for expression to iterate over the characters in a string, like such:
class Example {
def forString(s: String) = {
for (c <- s) {
// ...
}
}
}
and it is consistently failing with the message:
error: type mismatch; found : Int required: java.lang.Object Note that implicit conversions are not applicable because they are ambiguous: ... for (c <- s) { ^ one error found
I tried changing the loop to several things, including using the string's length and using hardcoded numbers (just for testing), but to no avail. Searching the web didn't yield anything either...
Edit: This code is the smallest I could reduce it to, while still yielding the error:
class Example {
def forString(s: String) = {
for (c <- s) {
println(String.format("%03i", c.toInt))
}
}
}
The error is the same as above, and happens at compile time. Running in the 'interpreter' yields the same.
Don't use the raw String.format
method. Instead use the .format
method on the implicitly converted RichString
. It will box the primitives for you. i.e.
jem@Respect:~$ scala
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) Client VM, Java 1.6.0_21).
Type in expressions to have them evaluated.
Type :help for more information.
scala> class Example {
| def forString(s: String) = {
| for (c <- s) {
| println("%03i".format(c.toInt))
| }
| }
| }
defined class Example
scala> new Example().forString("9")
java.util.UnknownFormatConversionException: Conversion = 'i'
Closer, but not quite. You might want to try "%03d"
as your format string.
scala> "%03d".format("9".toInt)
res3: String = 009
这篇关于斯卡拉:“隐式转换不适用”在一个简单的表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!