In Chapter 1
we saw several examples of how to define methods,
which are functions that are members of a class. Method
definitions start with the def
keyword, followed by optional argument lists, a colon character
(:
) and the return type of the method, an equals sign
(=
), and finally the method body. Methods are
implicitly declared “abstract” if you leave off the
equals sign and method body. The enclosing type is then itself abstract.
We’ll discuss abstract types in more detail in Chapter 5.
We said “optional argument lists,” meaning more than one. Scala lets you define more than one argument list for a method. This is required for currying methods, which we’ll discuss in Currying. It is also very useful for defining your own Domain-Specific Languages (DSLs), as we’ll see in Chapter 11. Note that each argument list is surrounded by parentheses and the arguments are separated by commas.
If a method body has more
than one expression, you must surround it with curly braces
({...}
). You can omit the braces if the method body has
just one expression.
Many languages let you
define default values for some or all of the arguments to a method.
Consider the following script with a StringUtil
object that lets you join a list of strings with a user-specified
separator:
// code-examples/TypeLessDoMore/string-util-v1-script.scala
// Version 1 of "StringUtil".
object
StringUtil
{def
joiner
(strings:List[String]
, separator: ...
No credit card required