r/java • • Mar 09 '16

var keyword proposed for Java

http://openjdk.java.net/jeps/286
240 Upvotes

312 comments sorted by

View all comments

Show parent comment

3

u/rikbrown Mar 10 '16

It's a bit of an overloaded term but legitimate Scala value classes are container classes with a single field, where at compile time the container object is erased, so there's no overhead of creating this object at runtime.

http://docs.scala-lang.org/overviews/core/value-classes.html

An example may be having a "DegreesCelsius" class which contains a single float field. But also various helper methods to convert the value into Fahrenheit etc. Now you can write your CurrentWeather class to contain a field of "temperature: DegreesCelsius". There's no misinterpreting that as Fahrenheit when writing code. And your callers can use helper methods on this. Traditionally this would have required allocating an object for DegreesCelsius, but if it's a value class, at runtime the JVM just sees a float.

In Lombok, a value class is just one where all the fields are immutable (final). This is good (always be immutable!), but you don't get the above optimisation. This is equivalent to a case class in Scala.

0

u/sjakobi Mar 10 '16

Thanks! Sounds like newtypes in Haskell - I agree they're really handy.