Scala:“隐式转换不适用”用简单的 for 表达

发布于 2024-10-28 18:49:22 字数 745 浏览 1 评论 0原文

我今天开始使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

久夏青 2024-11-04 18:49:22

不要使用原始 String.format 方法。而是对隐式转换的 RichString 使用 .format 方法。它将为您装箱基元。即

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'

更接近,但不完全。您可能想尝试使用 "%03d" 作为格式字符串。

scala> "%03d".format("9".toInt)
res3: String = 009

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
仅此而已 2024-11-04 18:49:22

Scala 2.81 产生以下更清晰的错误:

scala> class Example {
     |   def forString(s: String) = {
     |     for (c <- s) {            
     |       println(String.format("%03i", c.toInt))
     |     }                                        
     |   }                                          
     | }                                            
<console>:8: error: type mismatch;                  
 found   : Int                                      
 required: java.lang.Object                         
Note: primitive types are not implicitly converted to AnyRef.
You can safely force boxing by casting x.asInstanceOf[AnyRef].
             println(String.format("%03i", c.toInt))          
                                  ^                           

考虑到有关 String.format 的其他建议,这里是上述代码的最小修复:

scala> def forString(s: String) = {
     | for (c: Char <- s) {
     | println(String.format("%03d", c.toInt.asInstanceOf[AnyRef]))
     | }}
forString: (s: String)Unit

scala> forString("ciao")
099
105
097
111

在这种情况下,使用隐式格式甚至更好,但在如果您需要再次调用 Java 可变参数方法,这是一个始终有效的解决方案。

Scala 2.81 produces the following, clearer error:

scala> class Example {
     |   def forString(s: String) = {
     |     for (c <- s) {            
     |       println(String.format("%03i", c.toInt))
     |     }                                        
     |   }                                          
     | }                                            
<console>:8: error: type mismatch;                  
 found   : Int                                      
 required: java.lang.Object                         
Note: primitive types are not implicitly converted to AnyRef.
You can safely force boxing by casting x.asInstanceOf[AnyRef].
             println(String.format("%03i", c.toInt))          
                                  ^                           

Taking into account the other suggestion about String.format, here's the minimal fix for the above code:

scala> def forString(s: String) = {
     | for (c: Char <- s) {
     | println(String.format("%03d", c.toInt.asInstanceOf[AnyRef]))
     | }}
forString: (s: String)Unit

scala> forString("ciao")
099
105
097
111

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.

少女情怀诗 2024-11-04 18:49:22

我尝试了你的代码(带有额外的 println),它在 2.8.1 中工作:

class Example {
     | def forString(s:String) = {
     |   for (c <- s) {
     |    println(c)   
     |   }
     | }
     | }

它可以用于:

new Example().forString("hello")
h
e
l
l
o

I tried your code (with an extra println) and it works in 2.8.1:

class Example {
     | def forString(s:String) = {
     |   for (c <- s) {
     |    println(c)   
     |   }
     | }
     | }

It can be used with:

new Example().forString("hello")
h
e
l
l
o
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文