Functions
Key Concepts and Terminology
def vs. fn Functions
- def functions: Offer dynamism and flexibility similar to Python's
def. They allow for dynamic typing and do not require explicit type declarations for arguments or return types. Variables can be declared without var, and arguments are mutable.
- fn functions: Enforce strict type checking and memory safety, requiring explicit type declarations for arguments and return types. Arguments are immutable by default, promoting safer and more predictable code.
Type System
- Dynamic typing (def): Type inference occurs at runtime, allowing variables to be of any type. This flexibility comes with a risk of runtime errors due to unexpected types.
- Static typing (fn): Types are checked at compile time, reducing runtime errors and often improving performance.
Function Arguments
- Mutability: In
def functions, arguments can be modified within the function. In fn functions, arguments are immutable by default, preventing unintended side effects.
- Type declarations: Optional in
def but mandatory in fn, enhancing type safety in the latter.
- Variable declarations: Using
var is optional in def but required in fn.
Optional, Keyword, and Variadic Arguments
- Optional arguments: Functions can have arguments with default values, making them optional.
- Keyword arguments: Allow specifying arguments by name for clarity and flexibility in function calls.
- Variadic arguments: Enable functions to accept an arbitrary number of arguments, useful for functions like
sum.
Coding Examples Explained
def Function Example
def greet(name: String) -> String:
var greeting = "Hello, " + name + "!"
return greeting
def greet(name: String) -> String: defines a function greet taking a String as an argument and returning a String.