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()
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();
()
}
}
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With