Asrar
Asrar

Reputation: 31

Scala: function with no arguments

Im relatively new to scala functions and I'm getting confused on how this syntax sugar actually works and when to use a particular type.

I have written 3 functions all which should do the same thing, but I'm having problems understanding why Function0 is behaving differently

version 1

val fn1 : (String) => String = System.getProperty(_)

println(fn1("os.name"));

version 2

  val fn2 : () => String = System.getProperty("os.name")

  println(fn2());

Version 2 gives type mismatch; found : String required: () ⇒ String

version 3

val fn3 = () => System.getProperty("os.name")

println(fn3());

I understand that for version 2 scala already knows the return type of System.getProperty but why does it produce that particular error, why does it prevent me form explicitly stating the return type. I personally prefer explicit return types so I don't have to dive into a method to see what it is returning.

Upvotes: 1

Views: 1333

Answers (2)

Tim
Tim

Reputation: 3725

This version will typecheck:

val fn2 : () => String = () => System.getProperty("os.name")

Calling fn2() here is just like calling:

def fn2(): String = System.getProperty("os.name")
fn2()

In your fn1 example, the underscore is providing this implicit syntax, which looks a lot more like what you need for the empty-args case:

val fn1 : (String) => (String) = (s) => System.getProperty(s) 

Upvotes: 1

manojlds
manojlds

Reputation: 301327

In val fn2 : () => String = System.getProperty("os.name"), the System.getProperty("os.name") will be executed and return a string value. But you are saying fn2 is a value, which is a function that takes no arguments and returns a string.

When you do System.getProperty(_), it is like doing x => System.getProperty(x), which is a function that takes a string and returns a string. That is why first version works.

Upvotes: 4

Related Questions