8

A companion object for a trait in Scala has no visibility problems in Scala:

trait ProtocolPacket extends Serializable {    
  def toByteArray: Array[Byte]
}

object ProtocolPacket {
  def getStreamType( streamBytes: Array[Byte] ) = {
    // ...
  }
}

However on Java side (e.g. gets the above in a jar), a ProtocolPacket.getStreamType is not visible. In fact a (decompiled by IDEA) source does not have a getStreamType method defined for a ProtocolPacket

EDIT:

I found similar hits on SO regarding Companion$MODULE$, but was tricked by IDEA :) as shown below:

enter image description here

The above compiles and runs fine (shell and/or IDEA itself), in case anybody else gets trapped.

tolitius
  • 22,149
  • 6
  • 70
  • 81

2 Answers2

6

Looking at javap output you will find:

$ javap ProtocolPacket
public interface ProtocolPacket extends scala.Serializable{
    public abstract byte[] toByteArray();
}

and companion object:

$ javap ProtocolPacket$
public final class ProtocolPacket$ extends java.lang.Object implements scala.ScalaObject,scala.Serializable{
    public static final ProtocolPacket$ MODULE$;
    public static {};
    public void getStreamType(byte[]);
    public java.lang.Object readResolve();
}

this makes me believe in Java you can write:

ProtocolPacket$.MODULE$.getStreamType(/**/)
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

I think it's ProtocolPacket$.MODULE$.getStreamType() in Java but I haven't double checked.

See also How do you call a Scala singleton method from Java?.

Community
  • 1
  • 1
smparkes
  • 13,807
  • 4
  • 36
  • 61