Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Scala singletons from Java code

Tags:

java

scala

I have the following Scala (2.8) code:

object A {
  val message = "hello"
  object B {
    val message = "world"
  }
}

And a similar Java class:

public class C {
  public static String message() {
    return "HELLO";
  }
  public static class D {
    public static String message() {
      return "WORLD";
    }
  }
}

These work as I'd expect when I call them from Scala:

scala> A.message  
res0: java.lang.String = hello

scala> A.B.message
res1: java.lang.String = world

scala> C.message  
res2: java.lang.String = HELLO

scala> C.D.message
res3: java.lang.String = WORLD

But when I try something similar from Java, the compiler doesn't like the second line:

System.out.println(A.message());
System.out.println(A.B.message()); // cannot find ... symbol  : variable B ...
System.out.println(C.message());
System.out.println(C.D.message());

It's clear why this is the case when I look at the class files with javap. I know I can use

System.out.println(A$B$.MODULE$.message());

instead, or add something like val getB = B to my A object and replace the second line with

System.out.println(A.getB().message());

Is there a standard way to use nested Scala singleton objects from Java code?

like image 489
Travis Brown Avatar asked Aug 24 '10 18:08

Travis Brown


People also ask

What is the easiest way to implement singleton in Scala?

In Scala, a singleton object can extend class and traits. In Scala, a main method is always present in singleton object. The method in the singleton object is accessed with the name of the object(just like calling static method in Java), so there is no need to create an object to access this method.

How do I pass an argument to a Scala object?

you can access your Scala command-line arguments using the args array, which is made available to you implicitly when you extend App . As an example, your code will look like this: object Foo extends App { if (args. length == 0) { println("dude, i need at least one parameter") } val filename = args(0) ... }

What is Scala object in Java?

Scala Object and Class. Unlike java, scala is a pure object oriented programming language. It allows us to create object and class so that you can develop object oriented applications.


1 Answers

I'm have little knownledge of Scala, but considering the way Scala is compiled into bytecode, I think you have exposed the only two options you have.

like image 69
rds Avatar answered Sep 23 '22 14:09

rds