A definition like
def foo(x: Int) = x + 1
is nice and short and looks pretty, but when the signature itself gets uncomfortably long,
def foo[T <: Token[T]](x: ArrayBuffer[T], y: T => ArrayBuffer[() => T]): (T, T, BigDecimal) = {
// ...
}
I don't know where to split it. I find all of the following to look awkward:
def foo(
x: Int,
y: Int
): Int = {
// ...
}
def foo(
x: Int,
y: Int
): Int =
{
// ...
}
def foo(
x: Int,
y: Int
): Int
= {
// ...
}
def foo(
x: Int,
y: Int
):
Int = {
// ...
}
But, given that I'm going to have to get used to one of these, which will cause the least annoyance to my teammates?
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
Difference between Scala Functions & Methods: Function is a object which can be stored in a variable. But a method always belongs to a class which has a name, signature bytecode etc. Basically, you can say a method is a function which is a member of some object.
Here, Scala function is first-class value. Scala also has methods, but these differ only slightly from Scala function. A method belongs to a class; it has a name, a signature, [optionally, ] some annotations, and some bytecode. A function is a complete object that we can store in a variable.
The Scala style guide has nothing to say on this. In fact it recommends using methods with fewer parameters :-).
For function invocations it does recommend splitting so that each subsequent line aligns with the first parenthesis:
foo(someVeryLongFieldName,
andAnotherVeryLongFieldName,
"this is a string",
3.1415)
Personally in your case I would split according to a 'keep like things together' rule:
def foo[T <: Token[T]]
(x: ArrayBuffer[T], y: T => ArrayBuffer[() => T])
: (T, T, BigDecimal) = {
// ...
}
So the parameters are on one line, the return type is on a single line and the type restriction is on a single line.
In Haskell, long type signatures are often written in this fashion:
someFunc :: (Some Constraints Go Here)
=> Really Long Arg1 Type
-> Really Long Arg2 Type
-> Really Long Result Type
somefunc x y = ...
To translate this Haskellism into Scala,
def foo [ T <: Token[T] ]
( x : ArrayBuffer[T]
, y : T => ArrayBuffer[() => T]
) : (T, T, BigDecimal) = {
// ...
}
That's how I would do it. Not sure how kosher it is with the Scala community.
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