0
votes

Suppose we have this function definition and invocation:

def sayHello(prefix:String):(String => String) = {
  n => s"$prefix $n"
}

val greeting = sayHello("Hello")
greeting("Gio")

Using Intellij, I see the variable "n" inside function is of type String.

Why a variable not declared before is inferred by Scala as String?

I understand this higher order function returns a function String => String, but I can't see relationship between these two concepts.

Could you provide me a clarification about it?

1
What do you mean by "name not found" ?Jakub Zalas
I updated my postGiorgio
"Scala has a built-in type inference mechanism which allows the programmer to omit certain type annotations": docs.scala-lang.org/tour/local-type-inference.htmlMario Galic

1 Answers

4
votes

n in your example is not a variable. It's an argument (slight semantic difference). n => x notation represents a function accepting n and returning x.

Since you defined a return value of your sayHello to be a function String => String, the only thing you can return here is a function taking a String and returning a String. That's why you can skip the argument type for your n. With the current definition of sayHello it's clear, n can only be a String.

If you didn't define the return type of sayHello, scala would require you to give the type of the n argument, as it can't possibly infer it from the function definiton:

def sayHello(prefix:String) = {
    n: String => s"$prefix $n"
}

In the above example, the return value of sayHello is inferred from its body to be String => String.