Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

Scala Char automatically converts to Integer

Char is automatically converted to Integer. Why did this conversion from char to Int happen? I expected res2 to be of dataType anyVal.

val achar = 'a'
if (b > 12) 12 else achar
res2: Int = 97
question from:https://stackoverflow.com/questions/66066142/scala-char-automatically-converts-to-integer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is because you return a Int Value in the true-branch. Scala behaves with those primitive datatypes just like java (the classes are transformed into primitives through the compiler). So the return type of your if could be either a char or a int (12 is a integer, because number literals are always integers). Since a char could not hold every int, the compiler "casts" your char to a int. If you would cast 12 to a char like this:

val achar = 'a'
if (b > 12) 12.asInstanceOf[Char] else achar

It would return a char.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...