Kotlin. Functions. The fun keyword. Refactoring a function

Functions. The fun keyword. Refactoring a function. The return statement


Contents


Search other resources:

1. The concept of function. Function declaration syntax in Kotlin. The fun keyword. The return statement

A function is a named piece of code that can be called multiple times. Functions allow you to structure programs into logical-complete parts that interact with each other. Any large task is divided into a sequence of interrelated functions that use (call) each other.

Often in a program there is a repetition of some code more than once. It is advisable to design such code in the form of functions.

The programmer can implement his own set of functions, forming their libraries.

The function has the following properties:

  • the function can receive data in the form of parameters;
  • the function can return the result of some calculation.

A function declaration that returns a value begins with the fun keyword and has the following general form:

access_modifier fun FuncName(parameters) : Type {
  ...
}

here

  • FuncName is the name of the function. This name can be used to call the function;
  • access_modifier – one of the access modifiers private, public, internal, public;
  • parameters – a list of parameters that the function receives. Parameters are input data types and variable names that correspond to them. The function can receive from zero to several parameters. If the function receives no parameters, then these parameters are omitted. Function parameters are always read-only, as is the case with the val modifier;
  • Type – the type of the value returned by the function.

The curly braces { } indicate the body of the function – a sequence of statements that are executed when the function is called. The number of operators can be any.

If it is assumed that a function does not return a value, then the general form of declaring such a function is as follows:

access_modifier fun FuncName(parameters) {
  ...
}

If the function does not receive parameters and does not return a value, then the general form of declaring such a function looks even more simplified:

access_modifier fun FuncName() {
  ...
}

It is also allowed to declare a function using the following general form

access_modifier fun FuncName(parameters) = expression

here

  • expression is an expression that returns a single value. Such an expression can be, for example, an if-else statement or a when statement. It is important to understand that expression must return one value, therefore, the presence of an else component in this expression is required.

If a function returns a value and is implemented using the function body (curly braces {}), then the body code must end with a return statement, which has the following general form

return value

here

  • value – the value returned from the function. This value is the result of the return from the function.

 

2. Function call

Once declared, a function can be called from other code one or any number of times. The general form of a function call is as follows

FuncName(arguments)

here

  • FuncName – the name of the function being declared;
  • arguments – the arguments passed to the function. The arguments must match in terms of the number and compatibility of the parameter types, which are specified in the declaration of the function (see examples below).

 

3. Function declaration using refactoring. Sequence of steps

If there is a piece of code that needs to be formatted as a function, Intellij IDEA has a dedicated refactoring tool. To create a function using IntelliJ IDEA, in the code editor, follow these steps.

  1. Using the mouse or keyboard, select the fragment that you want to design as a function.
  2. In the area of the selected fragment, click the right mouse button. As a result, a context menu with a list of available commands will open (Figure 1).

Kotlin. IntelliJ IDEA. List of commands in the editor context menu

Figure 1. List of commands in the editor context menu

  1. In the context menu, select a sequence of commands Refactor -> Extract -> Function… (Figure 2) or press the key combination Ctrl+Alt+M. As a result, the “Extract Function” dialog box opens, refining the name and parameters of the function.

Kotlin. IntelliJ IDEA. The Function... command

Figure 2. The Function… command

  1. In the “Extract Function” window, you need to specify the name of the function, the list of function parameters and the visibility of the function from other parts of the program (Visibility). In our case, the generated window looks as shown in Figure 3. So far, the Visibility field has no significant meaning and it is left unchanged (private). The Name: field is set to Max2 and is the name of the function to create. Function parameters are selected a, b.

Kotlin. IntelliJ IDEA. The dialog box "Extract Function"

Figure 3. The dialog box “Extract Function”

After specifying the necessary parameters in the window and selecting the OK button, the system will generate the program code of the function and call this function as shown in Figure 4.

Kotlin. IntelliJ IDEA. The code of Max2() function

Figure 4. The code of Max2() function and function call, generated in IntelliJ IDEA

 

4. Examples of functions
4.1. A function that does not return a value and does not receive parameters

Task. Develop a Hello() function that prints the famous “Hello world!”

Solution. Since the task of such a function is to output previously known information (“Hello world!”), the function does not require any input parameters. Also, the function does not perform calculations, the result of which must be returned. Therefore, the function does not return a value.

Since the task of such a function is to output previously known information (“Hello world!”), the function does not require any input parameters. Also, the function does not perform calculations, the result of which must be returned. Hence, the function does not return a value. Therefore, the source code of the Hello() function with its call from the main() function is as follows

// Function Hello()
fun Hello() {
  println("Hello world!")
}

fun main(args:Array<String>)
{
  // The call of Hello() function
  Hello()
}

After starting, the program produces the following result

Hello world!

 

4.2. A function that takes parameters and returns a value
4.2.1. Calculating the characteristics of a figure by number

Task. Develop a Calc() function that takes two parameters:

  • figure number (1 – circumference, 2 – circle, 3 – sphere);
  • radius.

If you specify incorrect data, then the function should return 1.

Solution. A Kotlin program looks like this

// Function Calc()
fun Calc(numFig : Int, radius : Double) =
  when (numFig) {
    1 -> 2 * Math.PI * radius
    2 -> Math.PI * radius * radius
    3 -> Math.PI * Math.pow(radius, 3.0)
    else -> -1
  }

fun main(args:Array<String>)
{
  // Demonstration of using the Calc() function
  val radius : Double
  val number : Int

  print("Figure number (1..3) = ")
  number = readLine().toString().toInt()

  print("radius = ")
  radius = readLine().toString().toDouble()

  // Call the function and display the result
  val res = Calc(number, radius)
  print("res = " + res)
}

In the above code, the Calc() function has no return type. Because the type of the result is defined in the when operator. If you specify the correct figure number values (from 1 to 3), then the result type will be Double. If you specify an invalid value, the result type is Int.

The Calc() function itself is implemented without curly braces using the assignment operator (=).

Test example

Figure number (1..3) = 2
radius = 5.0
res = 78.53981633974483

 

4.2.2. Reversing a string

Task. Develop a ReverseString() function that reverses a string. The function returns a string that is the opposite of the original one. Demonstrate how the ReverseString() function works in the main() function.

Solution.

// Function ReverseString()
fun ReverseString(s : String) : String {
  var s2 : String = ""
  for (c : Char in s)
    s2 = c + s2
  return s2
}

fun main(args:Array<String>)
{
  // Demonstration of using the ReverseString() function

  // Some string
  val s = "abcde"

  // Call the function
  println(ReverseString(s)) // edcba
}

Program result

edcba

 

4.2.3. Determining the number of occurrences of a given character in a string

Task. Develop a function that takes two parameters:

  • source string;
  • character.

The function should return the number of occurrences of the specified character in the string.

Solution. The problem is solved by using a conventional linear search.

// Function CountCharToString()
fun CountCharToString(c : Char, s : String) : Int {
  var count = 0

  // Calculate the number of occurrences of the specified character in a string
  for (cc : Char in s)
    if (cc == c)
      count = count + 1

  // Return the result
  return count
}

fun main(args:Array<String>)
{
  // Demonstration of using the CountCharToString() function
  // Some string
  val str = "abcdef asdkjaldlk skdsjkl"

  // Invoke the CountCharToString() function
  // Calculate the number of occurrences of the character 's'
  val n = CountCharToString('s', str)
  println("n = " + n)
}

Program result

n = 3

 


Related topics