I am new to scala and I confused little bit with = and =>, I don't know in which scenario exactly = used and => used.
-
2= is for assignemnet and => to define the anonymous function – Raman Mishra Jan 04 '19 at 12:57
-
Without a grasp of the basics, don't worry about `=>`. It's a relatively advanced thing you shouldn't need to use unless you're intentionally trying to define anonymous functions, as @Raman says (or using things like `.map()`). – James Whiteley Jan 04 '19 at 13:43
1 Answers
@RamanMishra's comment is correct, however I would like to expand it a bit hopping it becomes more clear to you.
a = b means a is now equals to b (in the imperative meaning of the word, which is better understood as assignment).
It is used in many places, including when defining a function\method, for example
def sum(a: Int, b: Int): Int = a + b
The above statement can be readed as:
"We defined a function with name sum which takes two parameters (a & b) both of type Int and returns an Int. And its body\implementation is 'equals' to a + b".
a => b means, there is a function which takes a parameters list a and has a body b, it is used a couple of places, including anonymous functions and higher-order functions.
val anonymous: Int => Int = x => x + 1
The above statement can be readed as:
"We defined a value called anonymous, whose type is a function with one parameter of type Int and a return type Int, which is 'equals' to the 'anonymous' function which takes one parameter x (its type is inferred in by the context, in this type the explicit type signature before) and its body is x + 1"
def higherOrder(x: Int, f: Int => Int): Int = f(x)
The above statement can be readed as:
"There is a function (sum), which takes another function as a parameter (f), the later is a function of type Int to Int".
Edit
As @Aki suggested, the => is also used in pattern matching to separate the cases and the block of code to execute for each one.
def fact(n: Long): Long = n match {
case 0L => 1L
case n => n * fact(n - 1)
}
"This is somewhat similar to a parameter list => function body, as the above examples".
PS: This is a 101 Scala question, SO is not the best place for such questions, because there is probably enough resources on the internet - like this cheatsheet, or better places to ask - like the scala gitter channel.
- 21,686
- 3
- 28
- 45
-
You could also mention that the arrow is used in pattern matching after cases. – Aki Jan 04 '19 at 15:07
-
@Aki Good catch! - I totally forgot about it, I will edit the answer in a moment, thanks! – Luis Miguel Mejía Suárez Jan 04 '19 at 17:39