Lambda functions
So far, every function we have written belonged to a class or file, which could be treated as a class, but there is actually a way to define functions separately from any class definition. These kinds of functions are called lambda functions.
Creating a lambda function
Let’s take a look at a lambda function:
var print_hello: Callable = func(): print("Hello")
You can see that we’ve defined a function, just as we normally do, but this time without a function name. Instead, we assigned the function to a variable. This variable now contains the function in the form of the Callable
object type. We can call a Callable
object later on, like this:
print_hello.call()
This will run the function that we defined and, thus, print out Hello
to the console.
Lambda functions, just like normal functions, can take arguments too:
var print_largest: Callable = func(number_a: float, number_b: float): if number_a > number_b...