Skip to content

Instantly share code, notes, and snippets.

@oxbowlakes
Created October 4, 2012 07:44
Show Gist options
  • Save oxbowlakes/3832031 to your computer and use it in GitHub Desktop.
Save oxbowlakes/3832031 to your computer and use it in GitHub Desktop.
Defs in scala
// In scala a def (called a "method") is defined as follows:
def foo(arg: String): Int = expr
// ^ ^ ^^ ^ ^ ^
// ^ ^ ^^ ^ ^ an expression, whose type must match the declared return type, if specified
// ^ ^ ^^ ^ ^
// ^ ^ ^^ ^ the declared return type (optional).
// ^ ^ ^^ ^
// ^ ^ ^^ the type of each argument must be declared
// ^ ^ ^^
// ^ ^ ^each argument must be named
// ^ ^ ^
// ^ ^ zero or more "argument lists". Each argument list may have zero or more arguments
// ^ ^
// ^ the identifier (i.e. the name of the method)
// ^
// start with the keyword def
// Arguments may be given default values:
def driversLicense(tpe: String = "Standard: Cars")
// We "call" a method by providing values for the arguments:
driversLicense() //we can omit arguments if there are default values
driversLicense("HGV")
driversLicense(tpe = "Motorcycle < 125cc") //we can specify arguments by name
// It is idiomatic to specify arguments by name when they are booleans. E.g.
close(ignoreExceptions = true) //correct
close(true) //sadface
// We may declare defs within defs
def add(i: Int, j: Int) = {
def addI(j: Int) = j + i //Question: what value does j have here?
addI(j)
}
// "Variable shadowing". In the above definition, we use the name "j" twice. We say that the inner definition "shadows" the outer one.
// It may be a source of confusion but it is unambiguous; the definition in the closest enclosing scope is used
// We may omit the braces for methods composed of a single line, or unambiguous expression:
def add(i: Int, j: Int) = i + j
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment