1

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'
<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?

Charles
  • 50,943
  • 13
  • 104
  • 142
missingfaktor
  • 90,905
  • 62
  • 285
  • 365

3 Answers3

7

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.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
3

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

Community
  • 1
  • 1
raichoo
  • 2,557
  • 21
  • 28
2

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.

AndreasScheinert
  • 1,918
  • 12
  • 18