
Value Types for Java – A sketch of proposed enhancements - pjmlp
http://cr.openjdk.java.net/~jrose/values/values-0.html
======
gordaco
From the article, under "open questions":

 _Generics over values. It is persistent irritant that generics do not work
over primitive types today. With value types, this irritation will increase
dramatically; not being able to describe List <Point> would be even worse.
Still worse would be having it mean “today’s list, containing boxed points”.
Supporting generics over primitives and values, through specialization, is the
topic of a separate investigation._

The need for boxing/unboxing is for me one of the most common sources of
facepalm in Java. I guess it's difficult to fix without breaking existing code
(I guess that a new implementation of generics may not break java code, but it
would break existing bytecode), but it's really annoying.

~~~
pas
Java needs feature opt-in, import future.sane.Generics; and so on. (Scala has
these.)

Python learned it the hard way. The value of backward compatibility got a bit
underestimated there, with Java it's going the other way (the value of
progressing, giving better tools to developers is overlooked). The JVM is a
big bag of crazy code already (HotSpot with C1 and C2 JIT compilers, the many
garbage collector algorithms/implementations and the other stuff that is
currently deemed the JVM's responsibility), so there's plenty of space for new
opt-in features.

~~~
mcosta
Feature opt-in sounds good. The C++ people did it. Look what happened. Qt,
boost, gtkmm, mscf are all (more or less) good. But you can't (shouldn't) mix
them.

~~~
nly
> Qt, boost, gtkmm, mscf are all (more or less) good. But you can't
> (shouldn't) mix them.

I think you're missing the point of generic programming.

------
alkonaut
Feels like it needs proper (reified/runtime) generics in order to be useful.
Reified generics and value types would be a complete and long overdue break in
backwards compatibility.

But

It's a bit sad how java struggles to become a C# from five years ago. Would
make a lot more sense to leave java alone, add reified generics and value
types at the bytecode/vm level and instead launch a new language that could
use all of it.

Throw in pattern matching, algebraic data types and a bit more and I'm sold.

~~~
bad_user
> _Feels like it needs proper (reified /runtime) generics in order to be
> useful._

Actually type-erasure is one of Java's best features, because it didn't
cripple the runtime for other languages. For example Scala's type system is
too expressive to be built on top of .NET's generics.

First of all, reification only helps in terms of type-safety if you have a
weak type system. The only value that reification, as implemented in .NET
brings is specialization for value types.

Second of all, specialization can be done by the compiler. That's how many
languages have always done it. Scala for example has a @specialized annotation
for specializing type parameters for primitives [1]. And because this
functionality has some gotchas, there's also an up&coming project plugin
that's meant to be a replacement in future versions of Scala and that works
really well [2]

I myself have used the @specialized annotation on many occasions and in
general it does what it's supposed to do. And if that means I can develop in
languages like Scala, Clojure and JRuby on top of the JVM, then I really,
really love type-erasure. And oh, apparently one barrier for implementing
type-classes in F# are the generics in .NET ;-)

> _It 's a bit sad how java struggles to become a C# from five years ago_

What I find sad is grown men that can't see the forest from the trees. Java,
the language, is totally irrelevant and uninteresting and I like it that way,
because it's the kind of language you can rely on in case you want backwards-
compatibility (yes, that's a feature). On the other hand, the JVM is light-
years ahead of the CLR, because that's what the Sun, now Oracle engineers have
been doing with all of their time.

> _pattern matching, algebraic data types_

See Scala. It also does type-classes and higher-kinded types, amongst others
that F# is not capable of.

[1] [http://www.scala-
lang.org/api/2.10.3/index.html#scala.specia...](http://www.scala-
lang.org/api/2.10.3/index.html#scala.specialized)

[2] [http://scala-miniboxing.org/](http://scala-miniboxing.org/)

~~~
Locke1689
_Actually type-erasure is one of Java 's best features, because it didn't
cripple the runtime for other languages. For example Scala's type system is
too expressive to be built on top of .NET's generics._

...

People keep repeating this stuff and they're totally wrong. F* is _dependently
typed_ and is a CLR language.

bad_user, have you ever actually attempted to write a type unsoundness proof
for your claim or are you just repeating something you heard somewhere?

~~~
seanmcdirmid
There is nothing stopping a language implementer from ignoring CLR generics
and leveraging erasure to do their own thing. The problem is that such a
language is basically cut off from providing a bridge interface to any CLR
library that uses generics. I would guess this is why many core Microsoft
libraries (say WPF) don't use generics even though they could (but it could
just as much be that they were started before generics were pervasive in C#).

The LAMP team actually got pretty far with Scala on the CLR. The reason it
didn't go farther was more due to a lack of interesting and funding.

~~~
Locke1689
Yup, I mentioned this in a comment below -- interop is always the problem.
Then again, anyone who has looked under the hood and seen just how much MS
stuff is based on COM knows _all_ about that.

------
lmm
I'm excited about this not because I'd use them in Java, but because JVM
support for value types could make the case classes I'm using in Scala much
more efficient.

~~~
pron
That depends. Value types don't support polymorphism and subclassing. More
specifically, you can't have an array of a union value type like you would in
C. Could case classes do without polymorphism?

~~~
kasey_junk
Case classes as they currently stand cannot do without polymorphism. That said
the Scala team doesn't show a lot of hesitancy in adding new features so I
wouldn't be surprised if they implemented case value classes of some sort once
the JVM supports them natively.

------
acqq
How will the exiting libraries handle that? Would they be able to store the
whole "value objects" instead of just pointers to them?

That being said, not being Java programmer, I'd like to know what's the state
of the libraries now? Do libraries handle the collections of the primitive
types and the collections of the objects differently now, using the most
efficient infrastructure, or is it something that you have to select as the
programmer manually even now on case-by-case basis?

(edit: tried to adjust the terminology for Java)

~~~
taeric
I think the reality is that the vast majority of programmers don't find
themselves in situations where the boxing of values causes obvious performance
penalties. At least, not at the scale that shows up.

So, in general, most libraries just ignore collections of primitive types.

~~~
bhouston
It is hugely significant when doing 3D coding if you want to use the
convenience of vector and matrix types (and you really do because doing
operations on raw floats it not scalable and it is bug prone.)

Background: I did a lot of 3D app dev in Java in the 1998-2001 time frame and
then switched over to C#. C# was a huge improvement because it had value
types. When you have 5M vectors, you really do not want each to be its own
allocation.

~~~
taeric
Oh, I did not mean to imply it is not a huge factor where it matters. Probably
makes a bigger difference in standard CRUD fair apps than people realize.

My assertion is simply that compared to the cost of serializing to/from
database/user, it is probably not the pain point of many programmers. Hence,
most programmers probably don't think about it.

Just ask a few developers about the ridiculous overhead of HashSet<Integer>.
And then see how many places people still use it.

------
w01fe
Also perhaps interesting for comparison, a Clojure library called Vertigo that
emulates C structs with high performance on top of byte buffers:

[https://github.com/ztellman/vertigo](https://github.com/ztellman/vertigo)

~~~
lispm
Also perhaps interesting for comparison, a 1981 Lisp Machine library called
DEFSTORAGE provides structures on memory, based on a similar feature of PL/1\.
For example used in the Lisp Machine file system. Example from Symbolics
Genera:

    
    
        (defstorage (file-header)
          (version		fixnum)
          (logical-size		fixnum-bytes 2)
          (bootload-generation  fixnum)				;for validating
          (version-in-bootload  fixnum)				;used in above
    
          (number-of-elements	fixnum-bytes 2)			;for later expansion
          (ignore mod word)
    
          (* union
            (parts-array array 8 fh-element)
            (parts being fh-element				;and/or reformatting
                   fh-header						;this header itself
                   info						;header-resident info
                   header-fm						;file map of header
                   dire						;directory-entry-info
                   property-list
                   file-map
                   pad-area						;many natures of obsolescence
                   pad2-area)))

------
mnw21cam
Very interesting. Would possibly improve the performance of some programs, as
iterating over an array of value types will actually be sequential memory
access, whereas iterating over an array of objects involves skipping
everywhere over memory.

~~~
taeric
Does seem to go counter to a long standing culture of "let the VM decide" that
has dominated in the JVM landscape for a while.

I will be curious to see how this affects code targeting android and friends.

~~~
pron
Not quite. Unlike C# structs, this is not a memory-layout choice, but a
semantic choice. Value types have specific semantics: immutable, atomic, non-
extendable etc. It is up to the VM to choose how to lay them out in memory,
but an on-stack/inlined-in-array storage would be possible.

~~~
taeric
Oh, I miss understood and thought this was just about the memory layout
problem. Oops. :)

------
mhw
The linked article's title is "Value Types for Java". If you want to add some
context to the article, as you presumably do by posting it with the title
"Initial proposal for Java value types made public", can you do that by
posting a comment? For example, your title makes me wonder:

* Has the proposal progressed beyond this 'initial' version?

* What were the circumstances that led to it not being public originally?

* What circumstances have led to it having been made public now?

------
thescrewdriver
It's probably worth looking at how Scala implemented value types to get an
idea of a likely approach:
[https://docs.google.com/document/d/10TQKgMiJTbVtkdRG53wsLYwW...](https://docs.google.com/document/d/10TQKgMiJTbVtkdRG53wsLYwWM2MkhtmdV25-NZvLLMA/)

~~~
lmm
Not really the same thing - that only works for classes wrapping a _single_
value, not things like the given Point example.

~~~
frowaway001
The point is that the proposal now is pretty much identical with what Scala
people wanted in the first place.

The single-field restriction is there because there are limits in how
aggressive one can fight a non-cooperating runtime, not because it was their
principled choice.

------
eternalban
Possibly missing something here but couldn't the 'value type' distinction be
made with an annotation? I think that would be cleaner and possibly more
flexible as well.

~~~
jerven
Probably, (also makes back compatibility to earlier jvms easier). However, I
think the authors went for "horrible syntax in examples" so that we have time
to think about a final good/decent syntax. See what happened with lambas lots
of proposed syntaxes ended up with one decent one.

Here they want a discussion by implementers about the technical side and avoid
bikeshedding about syntax (for now).

------
kolev
The double underscores are ugly and foreign to Java's conventions.

------
bilalsoidik
MAKE VALUE TYPES ​​EASIER TO USE AND EXPLOIT THE TYPE INFERENCE CAPABILITIES
Hi! I have some ideas that I think They would be interesting on how to use
Values Types. I have two proposal: How to define if? and how to use it? The
two are separate proposal. I will write the first proposal.

1.Defining Value Types? A. What about forcing a primary constructor to
indicate that it is a value type, there is some thing like it in C#6, but in
C# it just to make easy to define a primary constructor. So in Java we can use
it differently. So we can say that if we use it that we are defining a value
type. It is possible to have more than one explicit constructor. But I don't
think that we have to force developer to write a constructor if it is not
necessary. Why? According to the document Value-types constructors are really
factory methods, so there is no new;dup;init dance in the bytecodes.

So I think that to define a value type we can only do: <p><pre><code> final
class Point(int x, int y){

boolean equals(Point p){ return this.x==p.x&&this.y==p.y}

}; </code></pre></p> x and y are automatically final and public members. So
that can exactly be compiled like: <p><pre><code> final __ByValue class Point
{ public final int x; public final int y;

    
    
        public Point(int x, int y) { 
            this.x = x;
            this.y = y;
        }
    
        public boolean equals(Point that) {
            return this.x == that.x && this.y == that.y;
        }

} </code></pre></p> Simple, concise and contributes to productivity. I also I
thought about something new. We can also do: <p><pre><code> final class
Point(int x, int y){ private int c;//if I wont boolean equals(Point p){ return
this.x==p.x&&this.y==p.y} public static Point getFunPoint(){ } public static
void maFunction(Point p, boolean b, double b){ } } </code></pre></p> B. Why
not an implicit default equals. So if I do : <p><pre><code> final class
Point(int x, int y){} </code></pre></p> that means if the JVM doesn't find an
explicit equals, it cans do logical compare. <p><pre><code> public boolean
equals(Point that) { return this.x == that.x && this.y == that.y; }.
</code></pre></p> So a Point can be defined in one line: <p><pre><code> final
class Point(int x, int y){} </code></pre></p> C. If we don't want to define
something else in a value type, braces can be optional as in lambda
expressions :) So to define a value type we can only do: <p><pre><code> final
class Point(int x, int y); </code></pre></p>

------
rurban
Instead of "Codes like a class, works like an int!" they probably meant "Codes
like a class, works like a struct".

The fact that a final class cannot be represented and optimized to a simple
struct in a non-dynamic language is really disturbing.

~~~
aardvark179
No, they did mean, "like an int." in that value types in java are intended to
be atomic and immutable in the same way primitives types already are and that
structs (in many languages) aren't.

------
bhouston
Only 14 years after it introduced with version 1.0 of C#. Java moves really
slowly these days. Java lost a lot of credibility in the 3D visualization
market in part because it is crazy inefficient to do 3D without value types.
C# did very well there with the XNA tool did in part because it had value
types and Java didn't.

I wouldn't have moved from Java to C# for desktop apps back in 2001 if Java
had stated they would have adopted value types quickly, but they didn't.

History has moved on though and Java isn't really used for desktop apps at all
now so this is a moot point. (And C# is on its last legs as well as a desktop
development tool, except in large organizations...)

Downvoted to -1 for stating a fact. That has never happened before. Edit
again, seems I've been upvoted again. Rollercoaster ride today.

~~~
pjc50
Large orgs developing apps for internal use are pretty much the only people
doing non-game desktop apps these days. They're still happy with it as an
inheritor of Visual Basic, and if you're happy to be Windows-only it works
very well.

I agree that Microsoft abandoning XNA development was a very disappointing
decision, it was a pretty good tool.

~~~
dman
What about the creative app industry - ie things like photoshop, indesign etc.

~~~
pestaa
Adobe is moving towards subscription-based cloud apps.

~~~
acqq
Subscription-based cloud apps but still developed in C++.

------
bborud
Would it kill them to format the article nicely?

------
wvenable
Does anyone else find the syntax choices for many of the new Java features to
be really distasteful? As a sacrifice to the gods of backwards compatibility,
Java syntax seems to going the way of C++.

~~~
cleverfoo
Yeah I totally agree. As much as I like lambdas in JDK8 the syntax feels super
bolt on. What's wrong with just {}, -> is just silly.

~~~
Alphasite_
Whats wrong with the () -> {} syntax? Its nice and simple, and scales down
well, so a -> a.b()

