Unlike Java, which does not allow you define functions outside of classes, both Kotlin and Java allow you to declare functions outside of classes.
func f(x : Int) -> Int {
return x*x + 2*x - 1
}
let result = f(x:13)
Parameters in Swift have both a label and a name. When you call a function you must use the label for each parameter. In the example above, x is both the label and the name for the sole parameter. If you want, you can use this syntax to specify separate labels and names for the parameters:
func g(input y : Int) -> Int {
return y*y - 1
}
let result = g(input:42)
Labels can also be blank, allowing the caller to pass a parameter without having to use a label for it.
func g(_ y : Int) -> Int {
return y*y - 1
}
let result = g(42)
Both languages allow you to declare default values for parameters that will be used when those parameters are missing in a function call.
func incr(_ x : Int, deltax : Int = 1) -> Int {
return x + deltax
}
var result = incr(42) // result is 43
result = incr(result,deltax:2) // result is 45
Swift, like Kotlin, makes extensive use of lambda expressions. Lambda expressions in Swift are called closures.
func filter(list:[Int],keep:(Int)->Bool) -> [Int] {
var result = [Int]()
for(x in list) {
if keep(x) {
result.append(x)
}
}
return result
}
func keepPositive(_ x:Int) -> Bool {
return x >= 0
}
let originalList = [2,-1,3,4,-6]
let filteredList = filter(list:originalList,keep:keepPositive)
Here is an example with different filtering functions where we use lambda expressions to eliminate the need to define a filtering function when calling filter():
let evens = filter(list:originalList,keep:{x in x%2==0})
Like Kotlin, Swift also allows trailing lambda expressions.
let evens = filter(list:originalList) { x in x%2==0 }
Finally, another shortcut form that both languages offer is an even shorter expression for a lambda where we don't have to declare the parameters for the lambda.
Kotlin uses the keyword it to stand for the sole parameter to a lambda expression in cases where the lambda has just one parameter.
let evens = filter(originalList) { it%2==0 }
Swift uses the place holders $1, $2, etc. to stand for the parameters to the lambda.
let evens = filter(list:originalList) { $1%2==0 }