Scala is Mad

I spent quick a bit of time to figure out why something that is usually simple to do in Java did not work in Scala: Arrays and ArrayLists with generics.

For some technical reason (type erasure at the JVM level), Array sometimes need a parameter with a ClassManifest !?! a generic type like [T :< Point : ClassManifest] need to be declared instead of simply [T :< Point].

And then the quickSort method somehow does not work if invoked on a generic... like quickSort(points) where points: Array[T]. I could not figure out yet how to do this one, I just casted to points.asInstanceOf[Array[Point]], quite ugly.

In contrast I did not even have to think much to write the Java equivalent. Generics in Scala, while having a nice syntax, are just crazy. This is something that goes beyond generics. Some of the Scala library and syntax is nice, but overall, the IDE integration is still very buggy, and productivity is not higher.

Update Dec 12 2012: here is the actual code (this is kept close to the Java equivalent on purpose):
object Point {
def sortAndRemoveIdenticalPoints[T <: Point : ClassManifest](points : Array[T]) : Array[T] = {
Sorting.quickSort(points.asInstanceOf[Array[Point]])
val l = new ArrayBuffer[T](points.length)
var previous = points(0)
l += points(0)
for (i <- 1 until points.length) {
if(math.abs(points(i).value - previous.value)< Epsilon.MACHINE_EPSILON_SQRT) {
l += points(i)
}
}
return l.toArray
}
return points
}
}

class Point(val value: Double, val isMiddle: Boolean) extends Ordered[Point] {
def compare(that: Point): Int = {
return math.signum(this.value - that.value).toInt
}
}
In Java one can just use Arrays.sort(points) if points is a T[]. And the method can work with a subclass of Point.

Comments

comments powered by Disqus