Scala:“隐式转换不适用”用简单的 for 表达
我今天开始使用 Scala,遇到了一个有趣的问题。我正在运行一个 for 表达式来迭代字符串中的字符,如下所示:
class Example {
def forString(s: String) = {
for (c <- s) {
// ...
}
}
}
并且它始终失败并显示消息:
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
我尝试将循环更改为几项,包括使用字符串的长度和使用硬编码数字(仅用于测试) ,但无济于事。搜索网络也没有产生任何结果...
编辑:这段代码是我可以将其减少到的最小代码,同时仍然产生错误:
class Example {
def forString(s: String) = {
for (c <- s) {
println(String.format("%03i", c.toInt))
}
}
}
错误与上面相同,并且在编译时发生时间。在“解释器”中运行会产生相同的结果。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要使用原始
String.format
方法。而是对隐式转换的RichString
使用.format
方法。它将为您装箱基元。即更接近,但不完全。您可能想尝试使用
"%03d"
作为格式字符串。Don't use the raw
String.format
method. Instead use the.format
method on the implicitly convertedRichString
. It will box the primitives for you. i.e.Closer, but not quite. You might want to try
"%03d"
as your format string.Scala 2.81 产生以下更清晰的错误:
考虑到有关 String.format 的其他建议,这里是上述代码的最小修复:
在这种情况下,使用隐式格式甚至更好,但在如果您需要再次调用 Java 可变参数方法,这是一个始终有效的解决方案。
Scala 2.81 produces the following, clearer error:
Taking into account the other suggestion about String.format, here's the minimal fix for the above code:
In this case, using the implicit format is even better, but in case you need again to call a Java varargs method, that's a solution which works always.
我尝试了你的代码(带有额外的 println),它在 2.8.1 中工作:
它可以用于:
I tried your code (with an extra println) and it works in 2.8.1:
It can be used with: