Kotlin Tips

Ali Göktaş
Sahibinden Technology
4 min readApr 16, 2021

Hi everyone. In this article, we will talk about “Kotlin Tricks”. We want to develops effective programs that’s why we should know some shortcuts about programming. Let’s try something with Kotlin.

Variable Definitions

I should use “var” or “val” before variable name for variable define.

Briefly:

val : For immutable variables (like “final” in Java)

var : For mutable variables

Error:

val data = “Ali Göktaş”

data = data + “ changed ”

Success:

var data = “Ali Göktaş”

data = data + ” changed ”

Lateinit

We do not always have to assign values to variables during definition. This is possible if we promise to make a definition later. It possible to lateinit.

Memory is not allocated until a value has been assigned.

If we don’t any assignment. An error occurs at runtime.

For example:

fun main() {
lateinit var foo:String

print(foo)
}

Exception returns!

Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property foo has not been initialized

Variable Type Coverage

Numbers:

Numeric values have a certain limit of space occupied in RAM memory. Each data type has different maximum and minimum values. For example, a variable defined as a “Short” data type can have a maximum of 32767 values.

Numeric types
Decimals

For example, the “Int” data type here does not include the “Short” data type. Although these values are the same number, they are not equal because they have different types.

String Templates

Kotlin provides to write codes in string templates. Let’s see details about the code blocks below.

$ and ${} usage
Logic Usage
$ and ${} usage

Ranges

Value ranges are fairly simplified in Kotlin language. It’s generally using for loop expressions.

fun main() {
var primeNumbers = listOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
for (index in 0..primeNumbers.count() - 1) {
print(primeNumbers[index])
print("\t")
}
}

Result:

2  3  5  7  11 13 17 19 23 29

Type Check

is — !is

It checks the fit of one object to another. Performs this check at run time.

var stringExample = "stringData"
var numberExample = 1
if(stringExample is String)
{
println("type is String")
}
else{
println("unknown type")
}

if(numberExample !is Double)
{
println("not a string")
}
else{
println("unknown type")
}

In the example above, there are conditions for equivalence as a type and absence. It returns true or false.

We’ll talk about intermediate tips in the next section.

Function

Extension Function

Extension functions are functions that can be added to your existing classes and called from resource classes.

class Circle (val radius: Double){
// member function of class
fun area(): Double{
return Math.PI * radius * radius;
}
}
fun main(){
// Extension function created for a class Circle
fun Circle.perimeter(): Double{
return 2*Math.PI*radius;
}
// create object for class Circle
val newCircle = Circle(2.5);
// invoke member function
println("Area of the circle is ${newCircle.area()}")
//invoke extension function
println("Perimeter of the circle is ${newCircle.perimeter()}")
}

Infix Function

Method calls look simpler and more aesthetic thanks to the Infix function. It cannot take parameters of type vararg.

A default value cannot be assigned to the parameter it takes.

fun main() {

infix fun Int.div(bolen: Int): Int = this / bolen;

// calling the function using the infix notation
15 div 5

// is the same as
15.div(5)
}

Every infix function is an extension function, but not every extension function is an infix function.

Thank you for your time.

References:

https://kotlinlang.org/docs/home.html

https://android.jlelse.eu/advanced-kotlin-tips-local-infix-and-inline-functions-tail-recursion-sealed-classes-and-more-2a53b00d5423

--

--