In this post I will talk about 5 cool things that functions can do in Kotlin, better than methods in Java.
1. Forget about overloaded methods
In Java, when you need the same method to have 1 parameter in one case and more parameters in another case, you would have to overload the method. This means to write another method with the same name, but different parameters. In Kotlin, this is history. You can provide default values for parameters, which are used when you do not provide all the corresponding arguments.
- Java
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sum(1); sum(1,2); } public int sum(int a, int b) { return a + b; } public int sum(int a) { return a + 2; } }
Kotlin
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) sum(1) sum(1, 2) } private fun sum(a: Int, b: Int = 2): Int { return a + b } }
2. A function can have as a parameter another function
A function that takes another function as parameter is called Higher-Order function.
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sum = sum(6, 3, { divide(6, 3) })// returns 11 Log.e("SUM", sum.toString()) } private fun sum(a: Int, b: Int, c: () -> Int): Int { return a + b + c() } private fun divide(a: Int, b: Int): Int { return a / b } }
3. We can create a function inside another function
A function that is created inside another function is called local function.
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sum = sum(6, 3) // the result should be 11 Log.e("SUM", sum.toString()) } private fun sum(a: Int, b: Int): Int { val y = a + b val z: Int fun divide(c: Int, d: Int): Int { // this is a local function return c / d } z = divide(a, b) return y + z }
4. We can create functions without name
A function that does NOT have a name, is called an anonymous function.
fun(x: Int, y: Int): Int { return x + y }
5. We can use lambdas
A lambda function is a simpler way of representing an anonymous function.
val sum = { a: Int, b: Int -> a + b }