1

Suppose I have:

trait Normalizer[T]{
   def apply(x:T):T
}

case class DoubleNormalizer() extends Normalizer[Double] {
  def apply(x:Double):Double {
     ... impl ...
  }
}

Does boxing/unboxing happen in either of the following cases, and would @specialized avoid it?

val d1:Normalizer[Double]
val d2:DoubleNormalizer

d1(123.4)  // boxes Double? (probably yes because d1.apply(T=Object)
d2(123.4)  // boxes Double? maybe not because s2.apply(Double) 

Without specialization, does the call to d2.apply receive a Double or an Object?

Feasibly:

  • the former because the compiler can prove at compile-time, the type of apply method is a double.

  • the later because DoubleNormalizer.apply(Double) is the implementation of Normalizer.apply(Object), and apply(Object) is the only concrete type signature that the JVM will provide.

user48956
  • 14,850
  • 19
  • 93
  • 154
  • See http://www.scala-notes.org/2011/04/specializing-for-primitive-types/ – Yawar Oct 06 '16 at 00:44
  • @Yawar thanks. I understand how specialized would affect this method called on the trait. But your referenced article is silent on when boxing/unboxing might happen in a subclass when the type is fully specified. Feasibly, it might box because the base class's method specification is generic, or it might not have to because at the point of calling the compiler can prove that a primitive double is only ever passed. Which is it? – user48956 Oct 06 '16 at 15:24
  • I'm short on time right now, but the article actually tells you how you can find out for yourself: `scalac -print Normalizer.scala` and examine the type-erased output. – Yawar Oct 07 '16 at 00:06

0 Answers0