Single Expression Functions

If one of our functions contains only a single expression, we can write the function out with shorthand syntax. This syntax allows us to create a function using only a single line of code.

For example, assume we create a function that returns a given number (num) to the power of 2. Using the normal function syntax, our code would look like this:

fun powerOf2(num: Int): Int { return num * num }

Using the single expression function syntax, we can rewrite the above code by removing the brackets ({ and }) as well as the return keyword:

fun powerOf2(num: Int): Int = num * num

Note how the return value (num * num) is prepended with an assignment operator (=).

We can shorten this code even more by removing the return type. Using type inference, the compiler can deduce the type of the return value, making our function look like this:

fun powerOf2(num: Int) = num * num



Create a single expression function called pyramidVolume().

The function will accept three Int types arguments: l, w, and h and return the value of (l * w * h) / 3.


Inside main(), create a variable called volume and set its value to pyramidVolume() with the following arguments in their respective order: length, width, height.

Use println() and a String template to output the following:

The volume of this pyramid is [volume].
Folder Icon

Take this course for free

Already have an account?