Saturday 31 July 2021

Android Java to Kotlin migration by example part 12: a few Kotlin features

Today I'm not going to use the format typical for this series, instead - I'll just show you two features of Kotlin I've just learned about. As there are no named arguments and default parameter values in Java, I cannot provide you the Java code counterpart this time :)

Kotlin functions have named arguments, actually exactly as in Python.

What that means (assuming you haven't read the previous post?). Well, let's consider the following code:

package com.mypackage

fun divide(nominator: Float, denominator: Float): Float{
return nominator/denominator
}
fun main() {

val result = divide(10.0f,5.0f)
val result2 = divide(nominator = 10.0f, denominator = 5.0f)
val result3 = divide (denominator = 5.0f, nominator = 10.0f)

println(result)
println(result2)
println(result3)
}

It produces the following result:

2.0 2.0 2.0

The function divide has (quite obviously) two arguments: nominator and denominator. If you call the function without specifying their names, their order matters: in our case, the first argument is divided by second one.

But... You can also call our function with named parameters: as in Python, here also it means you can switch their order (the calls initializing result2 and result3.

And second thing: also exactly as in Python, the parameters in Kotlin can have default values.

So that the following code, for example:

fun power(base: Float, exponent: Float = 2.0f): Float{
return base.pow(exponent)
}
fun main() {

val a2cubed = power(10f,3f)
var a2squared = power(10f)

println(a2cubed)
println(a2squared)
}

... makes power function actually a square function, when called with just one argument.

The code above produces the following result:

1000.0
100.0

I think that's all for today. Both named parameters and default values are neat features - especially in functional language - and another advantage of Kotlin over Java - it's good to know they're available.

No comments:

Post a Comment

Python crash course part 10: inheritance and polymorphism

In the last part we've shown how to create and use a class in Python. Today we're going to talk about inheritance: wchich means cre...