What is the difference between fun and fun () in Scala?

Here are two method declarations:

def fun = "x" def fun() = "x" 

Since they both don't need a parameter and return a String, what's the difference besides a method call?

+4
source share
4 answers

This is just a convention:

 obj.fun //accessing like property with no side-effects obj.fun() //ordinary method call, return value, but might also have side-effects 

Prefer the () version to emphasize that this is a method, not just a property.

Please note that this is just an agreement, a way to document code, the compiler does not apply the above rules.

+3
source

Besides the right to convention without a side effect for functions without parameters, there is an IS difference between "fun" and "fun ()" in Scala.

'fun' is called a function without parameters ', while the fun () function is a function with an 'empty parameter list'.

Shortly speaking:

 scala> def fun() = "x" fun: ()java.lang.String scala> fun res0: java.lang.String = x scala> fun() res1: java.lang.String = x scala> def fun = "y" fun: java.lang.String scala> fun res2: java.lang.String = y scala> fun() <console>:9: error: not enough arguments for method apply: (index: Int)Char in class StringOps. Unspecified value parameter index. fun() ^ 
+7
source

Functions without () are usually used to express functionality without side effects, as @Tomasz noted (for example, the length of a string - if you have the same string, the length will be the same)

If you define a function without parentheses, you cannot use them when calling a function:

 scala> def fun = "x" fun: java.lang.String scala> fun res0: java.lang.String = x scala> fun() <console>:9: error: not enough arguments for method apply: (n: Int)Char in trait StringLike. Unspecified value parameter n. fun() ^ scala> def fun() = "x" fun: ()java.lang.String //now you may use () or may not - it is up to you scala> fun res2: java.lang.String = x scala> fun() res3: java.lang.String = x 
+3
source

(Addenda) Here you can find the β€œpure vs side effect” agreement: Scala Style Guide Chapter 3.4.2

0
source

Source: https://habr.com/ru/post/1382500/


All Articles