Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Java equivalent of a Scala object?

In Scala, we can write

object Foo { def bar = {} }

How is this implemented by the compiler? I am able to call Foo.bar(); from Java but new Foo(); from Java gives the error cannot find symbol symbol: constructor Foo()

  • Does the JVM support singletons natively?
  • Is it possible to have a class in Java that does not have a constructor?

Note: here is the code output by scalac -print

package <empty> {
  final class Foo extends java.lang.Object with ScalaObject {
    def bar(): Unit = ();
    def this(): object Foo = {
      Foo.super.this();
      ()
    }
  }
}
like image 501
Jus12 Avatar asked Oct 19 '11 10:10

Jus12


People also ask

What is a Scala object?

In Scala, an object is a named instance with members such as fields and methods. An object and a class that have the same name and which are defined in the same source file are known as companions. Companions has special access control properties, which is covered under Scala/Access modifiers.

What is object type in Scala?

An object is a class that has exactly one instance. It is created lazily when it is referenced, like a lazy val. As a top-level value, an object is a singleton. As a member of an enclosing class or as a local value, it behaves exactly like a lazy val.

What is Scala object vs class?

Difference Between Scala Classes and Objects Definition: A class is defined with the class keyword while an object is defined using the object keyword. Also, whereas a class can take parameters, an object can't take any parameter. Instantiation: To instantiate a regular class, we use the new keyword.

Is everything an object in Scala?

Everything is an Object. Scala is a pure object-oriented language in the sense that everything is an object, including numbers or functions. It differs from Java in that respect, since Java distinguishes primitive types (such as boolean and int ) from reference types.


1 Answers

When compiling your code, Scala compiler produces an equivalent of the following Java code:

public final class Foo {
    private Foo() {} // Actually, Foo doesn't have constructor at all
                     // It can be represented in bytecode, 
                     // but it cannot be represented in Java language

    public static final void bar() {
        Foo$.MODULE$.bar();
    }
}

public final class Foo$ implements ScalaObject {
    public static final Foo$ MODULE$;
    static {
        new Foo$();
    }
    private Foo$() { MODULE$ = this; }
    public final void bar() {
        // actual implementation of bar()
    }
}

Here Foo$ is an actual implementation of a singleton, whereas Foo provides a static method for interaction with Java.

like image 122
axtavt Avatar answered Sep 28 '22 01:09

axtavt