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.

1
  • 1
    What does it look like in javap? Commented Feb 24, 2012 at 18:32

2 Answers 2

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(/**/)
Sign up to request clarification or add additional context in comments.

Comments

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?.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.