[sip 15] value classes and arrays

65 views
Skip to first unread message

martin odersky

unread,
Apr 23, 2012, 10:33:57 AM4/23/12
to scala...@googlegroups.com
There was some argument that we would like instances of value classes to be represented in unboxed form in arrays. Here's an exploration what this would mean. I am assuming we represent arrays as we represent them now. That is, monomorphic arrays are represented as in Java and polymorphic arrays are not wrapped or copied. We tried with great ingenuity to do otherwise in Scala up to 2.7 and failed. So let's not get back into that can of worms again.

Now, consider:

1:   val v: V = new V(1.0)
2:   val a: Array[V] = Array(v1)
3:   def f[T](b: Array[T]) = b(0) isInstanceOf V

If `a` in line 2 is represented as an unboxed double, then there is no way we can distinguish it from a double in the instanceof test in line 3. In other words, elements of value classes would behave differently from all other elements when it comes to type tests and pattern matches.

So to summarize: If we go for a kind of value classes that can be unboxed in arrays, these

 - cannot extend any traits
 - cannot override toString, equals, or hashCode
 - cannot support pattern matching or type tests

The last restriction means that we'd probably need some new declaration syntax for this new kind of value classes. They are clearly not the value classes specified in SIP 15. Probably not even call these types classes, because we seem to violate some fundamental aspects of classes, namely that they have a runtime type. In the following, I'll call them value newtypes instead.

So, for me, value classes and value newtypes have quite different properties. 

Only value classes make sense as implicit wrappers.
Only value classes can be seen as an optimization of plain classes.
Only value newtypes can be unboxed in arrays.

My inclination is to do value classes now, concentrate on making them work with specialization, and then evaluate whether FlatArrays are 
the right answer to storing them compactly in sequences. If that's not the case, we could investigate value newtypes as an alternative.

Your thoughts?

Cheers

 - Martin


Reply all
Reply to author
Forward
0 new messages