Confusion on Scala typing?

On the scala-user forum, someone posted the following Twitter exchange:

When a char becomes an Int
When a char becomes an Int

I investigated this and came to the conclusion that whenever two potential types appear in a val assignment like this, the “higher” type according to the type hierarchy is selected.

Here is some REPL output showing this:

scala> val x = if (false) '5' else '8'
x: Char = 8

scala> val x = if (false) '5' else 5.1111
x: Double = 5.1111

scala> val x = if (false) 5.111 else '8'
x: Double = 56.0

scala> val x = if (false) 5 else 5.1111
x: Double = 5.1111

scala> val x = if (false) 5.1111 else 5
x: Double = 5.0

So in the second part of that tweet, where val x is assigned to the result of the if statement, I think the Char was already converted to an Int, before it was printed out, whereas in the first part, like he says println expects an Any so since the ‘5’ is a char it can roll with that.

Interesting! Maybe this shows a case where you should type your vals.

Leave a Reply

Your email address will not be published. Required fields are marked *