Kevin Meredith
Kevin Meredith

Reputation: 41909

Class Extends a Trait With/Without Parentheses

Looking at this code from Scala in Depth...

scala> trait Foo {
     |  def someMethod(): Int = 5
     | }
defined trait Foo

scala> class Main() extends Foo {
     |   }
defined class Main

Then, I created a new Main (without the parentheses).

scala> class Main extends Foo {}
defined class Main

What is the meaning the parentheses in class Main()? How about without parentheses?

Upvotes: 1

Views: 755

Answers (4)

Nathaniel Ford
Nathaniel Ford

Reputation: 21230

The answer to 'what is idiomatic' seems to actually depend on the function in question. According to Lift in Action's Appendix A:

"It is typically idiomatic within Scala to give methods that have zero arguments no trailing parenthesis if the function is referentially transparent."

Thus, Thing.foo, which has no side-effects (it's just retrieving a value), is fine. If foo has a side effect, it is idiomatic to write foo() so that readers know something else is going on. Either way, Scala assumes the parenthesis and does not make you write them.

Upvotes: 1

som-snytt
som-snytt

Reputation: 39577

5.3 of the spec:

If no formal parameter sections are given, an empty parameter section () is assumed.

This is different from methods, which can be parameterless.

When you write

class A

you are really writing

class A()

Moreover,

scala> class A(implicit i: Int)
defined class A

scala> new A
<console>:9: error: could not find implicit value for parameter i: Int
              new A
              ^

scala> new A()(1)
res1: A = A@32185a4a

scala> new A(1)
<console>:9: error: too many arguments for constructor A: ()(implicit i: Int)A
              new A(1)
              ^

Upvotes: 5

Alexey Romanov
Alexey Romanov

Reputation: 170745

In parentheses after the class name you have arguments of the primary constructor. In this case there are no arguments, so you can leave the parentheses out.

Upvotes: 2

dhg
dhg

Reputation: 52681

It's the same. If you leave the parentheses off it's the same as empty parentheses.

class A()
new A()
new A

class B
new B()
new B

It's all the same.

Upvotes: 3

Related Questions