Functions

Crystal Functions

Defining Crystal Functions

Crystal functions use def with typed or inferred returns.

Introduction to Crystal Functions

In Crystal, functions are defined using the def keyword. Functions can have typed or inferred return types, allowing for flexible and efficient code. This guide will walk you through the basics of defining and using functions in Crystal, including examples with both typed and inferred returns.

Defining a Function

To define a function in Crystal, you use the def keyword followed by the function name and an optional list of parameters. The function body contains the code to be executed.

In this example, the greet function takes no arguments and prints Hello, World! to the console. The return type is inferred as Nil since there is no explicit return value.

Functions with Parameters

Functions can accept parameters to work with data passed to them. Parameters can have explicit types, improving code readability and safety.

The add function takes two Int32 parameters and returns their sum, which is also of type Int32. Specifying parameter and return types ensures that the function behaves as expected.

Inferred Return Types

Crystal can infer the return type of a function if it is not explicitly specified. This feature allows for concise code while maintaining type safety.

In the multiply function, the return type is inferred based on the expression a * b. Crystal understands the operation and deduces that the result is an Int32.

Multiple Return Values

Crystal functions can return multiple values using tuples. This is useful for returning related data without creating a custom type.

The divide_and_remainder function returns both the quotient and the remainder of the division as a tuple. The return type is explicitly defined as a tuple of Int32 values.

Using Functions

Once defined, functions can be called by using their name followed by parentheses enclosing any necessary arguments.

This example demonstrates calling the functions add, multiply, and divide_and_remainder, showing how to handle multiple return values using tuple unpacking.

Previous
puts