Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: what's the difference between Any and AnyRef? [duplicate]

Tags:

scala

Just curious about the difference between type Any and AnyRef in Scala. Why does int belongs to AnyVal but string belongs to AnyRef?

For example:

val a: AnyVal = 3
val b: AnyRef = "1"
like image 410
Bin Avatar asked Oct 15 '25 06:10

Bin


1 Answers

Any is the supertype of all types. Any has two direct subclasses: AnyVal and AnyRef.

AnyVal represents value types. There are nine predefined value types and they are non-nullable: Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean.

AnyRef represents reference types. All non-value types are defined as reference types. Every user-defined type in Scala is a subtype of AnyRef. String in scala equals to java.lang.String and is the subtype of AnyRef.

structure of scala.Any

like image 108
Dong Avatar answered Oct 17 '25 21:10

Dong