Introduction to Function Parameters

Hello, budding developer! In this unit, we're exploring function parameters in Scala. Function parameters are the inputs given to functions. For instance, in println("Hello, world!"), "Hello, world!" is a parameter you are passing to the println() function. Parameters help functions adapt to specific pieces of information, making them incredibly versatile.

Writing a Function with a Single Parameter

We'll start by writing a function that takes a single parameter. This simple function will greet a user:

In this case, name is a parameter of the type String that our greetUser function uses. We use the def keyword to define a function and string interpolation with s" to include the variable in the string.

Writing a Function with Multiple Parameters

We can also create a function with multiple parameters. For example, a function could calculate a rectangle's area by accepting its length and width as parameters.

In this code, length and width are Int parameters but Scala supports different data types for parameters. For example, Int, Double, Boolean, String, Array, etc.

Handling Different Numbers of Parameters

A Scala function can take any number of parameters — even zero. Here's an example with three parameters:

Here's an example with zero parameters:

Lesson Summary

Congrats! You've explored the world of function parameters in Scala, delving into their definitions, uses, and types. It's now time to put these concepts into practice by defining and using function parameters. Our next lesson will cover Function Returns. Happy coding!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal