4

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"
Shaido
  • 27,497
  • 23
  • 70
  • 73
Bin
  • 53
  • 1
  • 4

2 Answers2

14

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

Dong
  • 141
  • 4
2

All of the Scala primitives such as Int, Boolean etc extend AnyVal interface

And all the Java primitives or better say java objects which are in java.lang library extends AnyRef interface

for more information read the unified types which says the following

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. Unit is a value type which carries no meaningful information. There is exactly one instance of Unit which can be declared literally like so: (). All functions must return something so sometimes Unit is a useful return type.

AnyRef represents reference types. All non-value types are defined as reference types. Every user-defined type in Scala is a subtype of AnyRef. If Scala is used in the context of a Java runtime environment, AnyRef corresponds to java.lang.Object

And in your example val b: AnyRef = "1" b immutable variable is treated as java.lang.Object dataType.

Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97