Funkcja Kotlin (z przykładem)

Spisie treści

W tym artykule dowiesz się o funkcjach; jakie są funkcje, ich składnia i jak stworzyć funkcję użytkownika w Kotlinie.

W programowaniu funkcja to grupa powiązanych instrukcji, które wykonują określone zadanie.

Funkcje służą do dzielenia dużego programu na mniejsze i modułowe fragmenty. Na przykład musisz utworzyć i pokolorować okrąg na podstawie danych wprowadzonych przez użytkownika. Możesz utworzyć dwie funkcje, aby rozwiązać ten problem:

  • createCircle() Funkcjonować
  • colorCircle() Funkcjonować

Dzielenie złożonego programu na mniejsze komponenty sprawia, że ​​nasz program jest bardziej zorganizowany i łatwiejszy w zarządzaniu.

Ponadto unika powtórzeń i umożliwia wielokrotne użycie kodu.

Rodzaje funkcji

W zależności od tego, czy funkcja jest zdefiniowana przez użytkownika, czy dostępna w bibliotece standardowej, istnieją dwa typy funkcji:

  • Funkcja biblioteki standardowej Kotlin
  • Funkcje zdefiniowane przez użytkownika

Funkcja biblioteki standardowej Kotlin

Standardowe funkcje biblioteczne są wbudowanymi funkcjami w Kotlinie, które są łatwo dostępne do użycia. Na przykład,

  • print() jest funkcją biblioteczną, która drukuje komunikat do standardowego strumienia wyjściowego (monitora).
  • sqrt()zwraca pierwiastek kwadratowy z liczby ( Doublewartość)
 fun main(args: Array) ( var number = 5.5 print("Result = $(Math.sqrt(number))") )

Po uruchomieniu programu wynik będzie następujący:

 Wynik = 2,345207879911715

Oto link do standardowej biblioteki Kotlin, którą możesz odkryć.

Funkcje zdefiniowane przez użytkownika

Jak wspomniano, możesz samodzielnie tworzyć funkcje. Takie funkcje nazywane są funkcjami zdefiniowanymi przez użytkownika.

Jak stworzyć funkcję zdefiniowaną przez użytkownika w Kotlin?

Zanim będziesz mógł użyć (wywołać) funkcję, musisz ją zdefiniować.

Oto jak możesz zdefiniować funkcję w Kotlinie:

 fun callMe () (// treść funkcji) 

Do zdefiniowania funkcji w Kotlinie funsłuży słowo kluczowe. Następnie pojawia się nazwa funkcji (identyfikator). Tutaj nazwa funkcji to callMe.

W powyższym programie nawias ( )jest pusty. Oznacza to, że ta funkcja nie przyjmuje żadnego argumentu. Dowiesz się o argumentach w dalszej części tego artykułu.

Kody w nawiasach klamrowych ( )to treść funkcji.

Jak wywołać funkcję?

Musisz wywołać funkcję, aby uruchomić kody wewnątrz jej treści. Oto jak:

 Zadzwoń()

Ta instrukcja wywołuje callMe()funkcję zadeklarowaną wcześniej.

Przykład: prosty program funkcyjny

 fun callMe() ( println("Printing from callMe() function.") println("This is cool (still printing from inside).") ) fun main(args: Array) ( callMe() println("Printing outside from callMe() function.") )

Po uruchomieniu programu wynik będzie następujący:

Drukowanie z funkcji callMe (). To jest fajne (nadal drukowanie od wewnątrz). Drukowanie poza funkcją callMe ().

callMe()Funkcja w powyższym kodzie nie przyjmuje żadnego argumentu.

Ponadto funkcja nie zwraca żadnej wartości (zwracany typ to Unit).

Weźmy inny przykład funkcji. Ta funkcja przyjmuje argumenty, a także zwraca wartość.

Przykład: dodaj dwie liczby za pomocą funkcji

 fun addNumbers(n1: Double, n2: Double): Int ( val sum = n1 + n2 val sumInteger = sum.toInt() return sumInteger ) fun main(args: Array) ( val number1 = 12.2 val number2 = 3.4 val result: Int result = addNumbers(number1, number2) println("result = $result") )

Po uruchomieniu programu wynik będzie następujący:

 wynik = 15

Jak działają funkcje z argumentami i wartością zwracaną?

Tutaj dwa argumenty numer1 i numer2 typu Doublesą przekazywane do addNumbers()funkcji podczas wywołania funkcji. Te argumenty nazywane są argumentami rzeczywistymi.

 wynik = addNumbers (liczba1; liczba2)

Parametry n1 i n2 akceptują przekazane argumenty (w definicji funkcji). Te argumenty nazywane są argumentami formalnymi (lub parametrami).

In Kotlin, arguments are separated using commas. Also, the type of the formal argument must be explicitly typed.

Note that, the data type of actual and formal arguments should match, i.e., the data type of first actual argument should match the type of first formal argument. Similarly, the type of second actual argument must match the type of second formal argument and so on.

Here,

 return sumInteger

is the return statement. This code terminates the addNumbers() function, and control of the program jumps to the main() function.

In the program, sumInteger is returned from addNumbers() function. This value is assigned to the variable result.

Notice,

  • both sumInteger and result are of type Int.
  • the return type of the function is specified in the function definition.
     // return type is Int fun addNumbers(n1: Double, n2: Double): Int (… )

If the function doesn't return any value, its return type is Unit. It is optional to specify the return type in the function definition if the return type is Unit.

Example: Display Name by Using Function

 fun main(args: Array) ( println(getName("John", "Doe")) ) fun getName(firstName: String, lastName: String): String = "$firstName $lastName"

When you run the program, the output will be:

 John Doe

Here, the getName() function takes two String arguments, and returns a String.

You can omit the curly braces ( ) of the function body and specify the body after = symbol if the function returns a single expression (like above example).

It is optional to explicitly declare the return type in such case because the return type can be inferred by the compiler. In the above example, you can replace

 fun getName (firstName: String, lastName: String): String = "$ firstName $ lastName"

z

 fun getName (firstName: String, lastName: String) = "$ firstName $ lastName" 

To tylko krótkie wprowadzenie do funkcji w Kotlinie. Polecane artykuły dotyczące funkcji:

  • Funkcje inline Kotlin
  • Funkcje wrostków Kotlina
  • Zakres funkcji Kotlin
  • Domyślne i nazwane argumenty Kotlina
  • Rekursja Kotlina
  • Funkcja rekurencyjna ogona Kotlina
  • Funkcja rozszerzenia Kotlin
  • Kotlin High-Order Functions & Lambdas

Interesujące artykuły...