Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala RedBlackTree syntax

I was looking at the source of the RedBlackTree file and I stumbled upon the definition for Tree, the relevant part of which I have copied here:

sealed abstract class Tree[A, +B](
@(inline @getter) final val key: A,
@(inline @getter) final val value: B,
@(inline @getter) final val left: Tree[A, B],
@(inline @getter) final val right: Tree[A, B])

I have 2 questions:

  1. How does @(inline @getter) compare to @inline @getter?
  2. Why are the vals qualified with final? (Isn't final redundant in this context?)
like image 325
Alex DiCarlo Avatar asked Jan 14 '13 07:01

Alex DiCarlo


1 Answers

The @(inline @getter) syntax is an example of a meta annotation, which tells the compiler that the @inline annotation should be placed on the generated getter method (as opposed to the constructer parameter, which would be the default here): meta annotations

The final marks the generated field and getter as final, so they cannot be overridden by subclasses.

This particular combination was used here to trick the Scala compiler into directly accessing the fields of Tree instances, instead of calling getters and relying on the JVM optimizer to perform proper inlining. Unfortunately Scala does not provide an officially supported way to use fields directly.

When the redblack tree was optimized for Scala 2.10 this gave the best performance. See the immutable TreeMap/TreeSet pull request for the gory details.

like image 79
Erik Rozendaal Avatar answered Sep 30 '22 20:09

Erik Rozendaal