Scala:';隐式转换不适用';用一种简单的表达方式
我今天从Scala开始,遇到了一个有趣的问题。我正在运行for表达式来迭代字符串中的字符,如下所示:Scala:';隐式转换不适用';用一种简单的表达方式,scala,for-loop,implicit-conversion,Scala,For Loop,Implicit Conversion,我今天从Scala开始,遇到了一个有趣的问题。我正在运行for表达式来迭代字符串中的字符,如下所示: class Example { def forString(s: String) = { for (c <- s) { // ... } } } 类示例{ def forString(s:字符串)={ 对于(c我尝试了您的代码(带有额外的println),它在2.8.1中工作: class Example { | def forString(
class Example {
def forString(s: String) = {
for (c <- s) {
// ...
}
}
}
类示例{
def forString(s:字符串)={
对于(c我尝试了您的代码(带有额外的println),它在2.8.1中工作:
class Example {
| def forString(s:String) = {
| for (c <- s) {
| println(c)
| }
| }
| }
不要使用原始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'
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))
^
scala>类示例{
|def forString(s:字符串)={
|为了(c)如果您显示更多/所有代码,这会有所帮助。您显示的代码片段似乎没有问题。发布显示问题的代码。如果文章太长,请删除其中的行,直到获得显示问题的最小示例。您甚至可能会发现问题所在。我很难选择要选择的答案…但我最终选择了这里用a+1。我同意;这个答案解释了如何进行代码类型检查,但另一个答案解释了您最好编写什么代码(如我所说);因此它们是互补的。无论如何,谢谢,我很感激!更简单的是c:Integer
。
new Example().forString("hello")
h
e
l
l
o
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'
scala> "%03d".format("9".toInt)
res3: String = 009
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))
^
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