Using @ specialized in features

I have a trait and implementation similar to:

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. Is it necessary to use it both in properties and in implementation, only in implementation, or only in features?

+6
source share
1 answer

REPL has the right answer for us along with javap, which will show the disassembled Java code. If you add tools.jar to your path to the REPL class, you can 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 it is enough to provide only the @specialized option only at the attribute level: in the Foo interface, you obviously have two method declarations. It seems to me that there is a trick here:

 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 that I cannot answer:

  • Why are methods defined as a public annotation in a feature?
  • Why does the doSomething method (java.lang.Object) exist in a disassembled class, but cannot be called?
+3
source

Source: https://habr.com/ru/post/913440/


All Articles