Single-line functions (also known as one-expression functions) in Kotlin are functions that consist of only one expression and without curly braces {} To be defined. They help improve the readability and compactness of the code, especially for simple and short functions. The syntax of a Single Expression Function in Kotlin has the following structure:

  • fun – The keyword to define a function.
  • functionName – The name of the function.
  • parameter1, parameter2, … parameters – The list of parameters expected by the function. Parameters are in parentheses () enclosed and separated by commas.
  • ReturnType – The type of value the function returns. This part is optional if the compiler can automatically infer the return type.
  • = – The equal sign that marks the start of the expression of the one-line function.
  • expression – The expression that represents the body of the function and calculates the result of the function.

An example of a one-line function that calculates the sum of two numbers:

Another example in which a one-line function calculates the square of a number:

A function that returns the larger of two numbers:

Your content here

Leave a Comment

Your e-mail address will not be published. Required fields are marked with * marked