开发者

Misleading compile time error

Why does the following compile?

scala> val ch1 = 'a' + 'b'
ch1: Int = 195

but the following doesn't?

scala> var ch1 = 'a'
ch1: Char = a

scala> ch1 += 'b'
开发者_C百科<console>:9: error: type mismatch;
 found   : Int
 required: Char
       ch1 += 'b'
           ^

scala> ch1 = ch1 + 'b'
<console>:8: error: type mismatch;
 found   : Int
 required: Char
       ch1 = ch1 + 'b'
                 ^

And why is the error message so misleading? Why does it say required: Char when what I am passing is clearly a Char?


When you add a Char and another Char, the result is an Int.

scala> 'a' + 'c'      
res2: Int = 196

That's the "found" part of the error message.


This might help:

What is the concept of "weak conformance" in Scala?

http://lmazy.verrech.net/wp-content/uploads/2011/02/scala_type_hierarchy.png

Regards, raichoo


I guess you have to help the compiler here if you annotate the ch1 as Int it works as expected? The problem is I guess your intend is misread by the compiler :) How should it know that you declare a Char to get it's int value to add another Int out if it? You are trying to change the type of a variable after assignment , how could , should that work? So start with var ch1:Int='a' and it works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜