Please Explain this "Value classes are classes whose instances are not represented as objects by the underlying host system."

Value classes are classes whose instances are not represented as objects by the underlying host system. Can anyone explain this sentence to me?

I think I can. =)

Given some value class defined as such:

case class StringWrapper(str: String) extends AnyVal

And some case class that uses this:

case class MyThing(strw: StringWrapper)

When you create a new instance of MyThing you’ll create a StringWrapper in your Scala code, but in the computer’s memory while the application is running the only thing the JVM would see is a String. The value class you defined wrapping the string is stripped away by the compiler. So if you were to do a heap dump of your application or do some Java reflection on your object, all you would ever see is a String.

Does that make sense?

This is especially useful on the JVM when the value is a primitive as that allows for stack allocation and handling so there is less memory consumption and, if you are making lots of them, less memory churn for the GC to deal with.

It means that JVM won’t have any idea of our class extends AnyVal. Ok, makes sense. Thank you. Any idea why do they only suppprt defs and not vals or vars?

At runtime your value class StringWrapper is erased to String so there is only room for the one String that it’s wrapping. A val and a var require a field in an object but at runtime there is no object.

But keep in mind that there are many cases when the wrapper object will be allocated. More info here.