Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Scala know the difference between "def foo" and "def foo()"?

Tags:

scala

I know about the usage difference between empty-parameter and parameterless methods in scala, and my question pertains to the class file generated. When I look at these two classes in javap, they look exactly the same:

class Foo {
  def bar() = 123;
}


class Foo {
  def bar = 123;
}

But when I look at them in scalap, they accurately reflect the parameter lists. Where in the class file is scalac making this distinction known?

like image 667
Chuck Adams Avatar asked Apr 12 '12 19:04

Chuck Adams


People also ask

Should I use def or Val for defining a function in Scala?

For the most part — maybe 98% of the time — the differences between defining a “function” in Scala using def or val aren’t important. As I can personally attest, you can write Scala code for several years without knowing the differences. As long as you’re able to define a val function or def method like this:

What does Def Foo = 42 mean in Scala?

Similarly, foo (42) is short for foo.apply (42), and foo (4) = 2 is short for foo.update (4, 2). This is used for collection classes and extends to many other cases, such as STM cells. Scala distinguishes between no-parens ( def foo = 42) and empty-parens ( def foo () = 42) methods.

What is the diff function in Scala?

The diff function is applicable to both Scala's Mutable and Immutable collection data structures. The diff method takes another Set as its parameter and uses it to find the elements that are different from the current Set compared to another Set. As per the Scala documentation, the definition of the diff method is as follows:

How are Def methods in Scala classes compiled into Java classes?

As you might suspect, a def method in a Scala class is compiled into a similar method on a Java class. To demonstrate this, if you start with this Scala class: you can then compile it with scalac. When you compile it with the following command and look at its output, you’ll find that there’s still a method in a class:


1 Answers

In the .class file, there is a class file attribute called ScalaSig, which contains all of the extra information needed by Scala. It's not really readable by humans, but it is there:

$ javap -verbose Foo.class
const #195 = Asciz      ScalaSig;
const #196 = Asciz      Lscala/reflect/ScalaSignature;;
const #197 = Asciz      bytes;
const #198 = Asciz      ^F^A!3A!^A^B^A^S\t\tb)^[7f^Y^Vtw\r^^5DQ^V^\7.^Z:^K^E\r!^
Q^A^B4jY^VT!!^B^D^B^UM^\^W\r\1tifdWMC^A^H^....

See also How is the Scala signature stored? and scala.reflect.ScalaSignature, which isn't very interesting :-)

like image 154
Matthew Farwell Avatar answered Oct 05 '22 17:10

Matthew Farwell