- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 325字
- 2021-06-10 18:49:20
Functions
The fun keyword is used to define functions in Kotlin. In this section, we'll discuss writing a function, type inference, and specifying the return type.
In the following example, we create a function that takes two arguments of the String type and prints them to the console.
Consider the following code for 6_Function.kts:
fun welcome(name:String, msg:String) {
println("$msg $name")
}
welcome("Bob", "hello")
Note that we used string template to print the values without concatenating string literals.
The output of the preceding code as follows:
This is a simple example of creating a function and invoking it. Now, let's create a function that returns a value.
Consider the code for 6a_Function.kts:
fun welcome(name: String, msg:String) =
"$msg $name"
println(welcome("Bob", "hello"))
The output is as follows:
The = symbol says that Kotlin should infer the type from the context and identify the return type of the function. This is more suitable for single-line functions. For complex functions, we can specify the return type, in this case a String, and the return statement in the function, as shown here.
Consider the code for 6b_Function.kts:
fun welcome(name: String, msg:String) : String {
return "$msg $name"
}
println(welcome("Bob", "hello"))
The output is as follows:
We specified the String return type after the arguments prefixed by the colon (:) and the return statement in the function body.
Let's take a look at a function that doesn't return anything. We are interested in writing the void function.
Consider the code for 6c_Function.kts:
fun addNumbers(x: Int, y:Int) : Unit {
println("Sum of numbers is ${x+y}")
}
addNumbers(2, 3)
The output is as follows:
Unit is the representation of void in Kotlin. We can also write a void function without the Unit, as shown here.
Consider the code for 6d_Function:
fun addNumbers(x: Int, y:Int) {
println("Sum of numbers is ${x+y}")
}
addNumbers(2, 3)
The output is as follows:
- Access 2016數(shù)據(jù)庫(kù)管
- Visual C#.NET程序設(shè)計(jì)
- ArcGIS for Desktop Cookbook
- ExtJS Web應(yīng)用程序開(kāi)發(fā)指南第2版
- C++ Fundamentals
- Mastering Concurrency Programming with Java 9(Second Edition)
- Angular Design Patterns
- DB2SQL性能調(diào)優(yōu)秘笈
- Elastix Unified Communications Server Cookbook
- AI輔助編程Python實(shí)戰(zhàn):基于GitHub Copilot和ChatGPT
- 計(jì)算機(jī)軟件項(xiàng)目實(shí)訓(xùn)指導(dǎo)
- 精通Oracle 12c 數(shù)據(jù)庫(kù)管理
- 跟著迪哥學(xué)Python數(shù)據(jù)分析與機(jī)器學(xué)習(xí)實(shí)戰(zhàn)
- 區(qū)塊鏈社會(huì):區(qū)塊鏈助力國(guó)家治理能力現(xiàn)代化
- Elixir Cookbook