What does this mean when I use def to define a field in Scala?

What is the difference between:

scala> def foo = 5 foo: Int 

and

 scala> def foo() = 5 foo: ()Int 

It seems that in both cases, I get the variable foo , which I can access without parentheses, always evaluating 5 .

+6
scala
source share
4 answers

You do not define a variable in any way. You define a method. The first method does not have parameter lists, the second has one parameter list, which is empty. The first one should be called like that

 val x = foo 

while the second should be named like that

 val x = foo() 

However, the Scala compiler allows you to call methods with one empty parameter list without parentheses, so any form of call will work for the second method. Methods without parameter lists cannot be called with parentheses

Scala's preferred style is to define and call methods without arguments that have side effects with parentheses. Methods without arguments without side effects should be defined and called without parentheses.

If you really define a variable, the syntax is

 val foo = 5 
+16
source share

Before anything else is said, def does not define a field; it defines a method.

In the second case, you can omit the parentheses due to the specific Scala function. There are two distinctive features here: one mechanical and one of the recommended applications.

Starting with the latter, it is recommended to use an empty parameter list when there are side effects. One classic example is close() . You would not mark parentheses if there are no side effects to invoke the item.

Now, as a practical difference β€” beyond the potential for strange syntactic confusion in angular cases (I'm not saying that it is, just a hypothesis) β€”structure types must follow the correct convention.

For example, Source had a close method without parentheses, which means that the structural type def close(): Unit will not accept Source . Similarly, if I define a structural method as def close: Unit , then Java closeable objects will not be accepted.

+6
source share

What does this mean when I use def to define a field in Scala

You cannot define a field using def .

It seems that in both cases, I get the variable foo, which I can access without parentheses, always evaluating to 5.

No, in both cases you get a foo method that you can call without parentheses.

To see this, you can use javap :

 // Main.scala object Main { def foo1 = 5 def foo2() = 5 } F:\MyProgramming\raw>scalac main.scala F:\MyProgramming\raw>javap Main Compiled from "main.scala" public final class Main extends java.lang.Object{ public static final int foo2(); public static final int foo1(); } 

However, see http://tommy.chheng.com/index.php/2010/03/when-to-call-methods-with-or-without-parentheses-in-scala/

+4
source share

In addition to the answers already indicated, I would like to emphasize two points:

+3
source share

All Articles