I have a trait and an implementation looking like:
trait Foo[A] {
def bar[B >: A: Ordering]: Foo[B]
}
class FooImpl[A]( val a: A, val values: List[Foo[A]] ) extends Foo[A] {
def bar[B >: A] = { /* concrete implementation */}
}
I would like to use the @specialized
annotation on A
and B
to avoid autoboxing. Do I need to use it in both trait and implementation, only in implementation, or only in trait ?
The REPL has the right answer for us, together with javap, which will show the disassembled java code. If you add tools.jar to your REPL classpath, you will be able to do cool things like the following:
scala> trait Foo[@specialized(Int) A] { def doSomething(a:A)}
defined trait Foo
scala> :javap -p Foo
Compiled from "<console>"
public interface Foo{
public abstract void doSomething(java.lang.Object);
public abstract void doSomething$mcI$sp(int);
}
scala> class Hello extends Foo[Int] { def doSomething(a:Int)=println(a)}
defined class Hello
scala> :javap -p Hello
Compiled from "<console>"
public class Hello extends java.lang.Object implements Foo$mcI$sp,scala.ScalaObject{
public void doSomething(int);
public void doSomething$mcI$sp(int);
public void doSomething(java.lang.Object);
public Hello();
}
So now it should be clear to you that providing the @specialized only at trait level is enough: in the Foo interface you clearly have two method declaration. It looks to me that a trick is going on there, however:
scala> new Hello
res0: Hello = Hello@7a80747
scala> res0.doSomething("test")
<console>:11: error: type mismatch;
found : java.lang.String("test")
required: Int
While I can answer your question, there are some questions which I can't answer:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With