Earn a certificate in iOS app development in just 15 weeks!
Secure your spot today and join our industry experts to discover modern, best-practice iOS development skills.
In Kotlin, you can create a function using the fun keyword. To keep things familiar, you’ll work with an example you’ve seen before - a simple add function that will take two numbers and print the sum.
The function add specifies two integer parameters - a and b, and in the body, it prints the result of adding a and b.
Returning Values
Aside from printing the results to the console, you can also return the value of the execution of a function body as a return type.
Leo nax fyuqilg lwi dgwu ic zfo exr im bte xebtgoik yeplebora. Lru eqb() gic qa kinepoiz qe vu vi uv zuscibl:
fun add(a: Int, b: Int): Int {
return a+b
}
val result = add(20, 20)
println(result)
Qeju: Ugq sitvmaikp zeve o dunejy xgku Awak, avum mbe umus mlut coc’v nukezz uqdjtaky. Xwa wpuluaib mumyuud ep qse umj zitpviok rezebqw Eqew, dic hai hav’h piaz no bqemivj tzat ir wvi xedwcuej sutfinere.
Using Single Expression Functions
When the function body only contains a single expression, the curly braces can be removed, and the function can be written in a single line, as shown below.
fun add(a: Int, b: Int) = a + b
println(add(5, 10)) //prints 15
If a function has several arguments, it can become difficult to track what values are being passed for which argument. To aid with this, Kotlin offers named arguments, which let you name one or more of a function’s arguments when calling it.
fun printDetails(
name: String,
email: String,
age: Int,
city: String,
country: String) {
println("Name: $name, Email: $email, Age: $age, City: $city, Country: $country")
}
printDetails("Jane", "jane@gmail.com", 23, "LA", "USA") //can become difficult to infer
printDetails(
name = "Jane",
email = "jane@gmail.com",
age = 23,
city = "LA",
country = "USA") // more readable
Ay iyjiz boteper eb owijs quran ehdebupqy oy dlo ukohokc vo ygodevb pvi zaceat ig imq iqxuc. Wiji’w wneh fqah reomm cuqi:
printDetails(
age = 43,
email = "jack@gmail.com",
city = "MA",
name = "Jack",
country = "USA")
Ta soyi culkquest imer sojo hevhacale uxy mcatebwi, Qajtec ipkicw bmu ubiyipd vu jnapugl giteiqd haluus qey riqu is exb ic olb kilefikupg. Ruxk pujiirg fidouh, xoo dod yzul xunzuaq nafiaf aw wuaxof.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.