If I create a function:
def a(): String = return "some string"
the result would be "a: ()String" So I can use it with/without brackets
On the other hand if I create the same function
def a:String = return "some other string"
It would be just "a: String" and in this case I can't use it with brackets.
What is the difference between these two?
A nullary or niladic function.
Functions do not have declared return types. A function without an explicit return statement returns None . In the case of no arguments and no return value, the definition is very simple. Calling the function is performed by using the call operator () after the name of the function.
In these cases, we can call our function without specifying the values for the parameters with default arguments. To do this in Python, we can use the = sign followed by the default value.
*args allows us to pass a variable number of non-keyword arguments to a Python function. In the function, we should use an asterisk ( * ) before the parameter name to pass a variable number of arguments.
Good practice recommends defining functions that have no side effect without ()
, and to add the ()
both at definition site and call site when the function has side effects (e.g., println()
rather than println
).
If you define a
like this, without parentheses (note, the return
keyword is not necessary):
def a: String = "some other string"
and then call it with parenthesis: a()
, then the ()
is not the empty argument list for the method a
; instead, Scala will try to apply the ()
to the String that method a
returns. The error message that you get when you try that hints to that:
scala> a()
<console>:7: error: not enough arguments for method apply: (n: Int)Char in trait StringLike.
Unspecified value parameter n.
a()
^
So, in the second case, a()
means something else than in the first case. In the first case, it just means "call a
with an empty argument list", and in the second case it means "call a
, then apply ()
to the result of the method", which will fail on a String
.
edit To expand on your second question in the comments below, it depends on what exactly you mean by "the same thing". As you saw in the REPL one looks like it has the type ()java.lang.String
while the other has the type java.lang.String
. Have a look at the following, in which x
and y
turn into the same thing:
scala> def a() = "aaa"
a: ()java.lang.String
scala> def b = "bbb"
b: java.lang.String
scala> val x = a _
x: () => java.lang.String = <function0>
scala> val y = b _
y: () => java.lang.String = <function0>
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