Suppose I want to assign an anonymous function which maps an Int to an Int
I could assign it like this
val double = (x: Int) => x * 2
or like this
val double: Int => Int = x => x * 2
Which one is more idiomatic? Or are there situations where one is preferable to the other?
I’d call it twice because
doubleis a reserved word in Java and may prompt confusion with the data typeDouble(i.e.doublein Java). In any case, neither is really more idiomatic than the other. All else being equal, I would prefer the first form since it is shorter and will automatically fix my types for me if I decidexshould be aFloat(i.e. I’ll only have to change the type in one spot). I’d favor the second if I decided it was important yet non-obvious that it was anInt => Int, or if the case was more complicated and it needed that information to do proper type inference. Actually, in this simple situation I’d write the cases aswhich makes them the same length. (I’d still favor the first one since it is no longer and in cases where you need to refer to the variable more than once you can keep the same form.)