Welcome to part 2 of my series on Kotlin. If you haven’t already, make sure you go back and read Why Kotlin is Dope: Part 1.

Toasts

Really not much of a difference here, just no semicolon.

Java

Toast.makeText(context, "hello world!" , Toast.LENGTH_SHORT).show();

Kotlin

Toast.makeText(context, "hello world!", Toast.LENGTH_SHORT).show()

Filters

Java

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
numbers.stream()
    .filter(value -> value > 5)
    .forEach(System.out::println);

Kotlin

    val numbers = listOf(1,2,3,4,5,6,7,8,9,10)
    println(numbers.filter{ it > 5}.toString())

Extensions

Extensions in Kotlin are a way to extend a class with new functionality. The most basic example of this is when we used to create a BaseActivity class in Java and have all the other activities in our project use inheritance MainActivity extends BaseActivity. I find Kotlin extensions to be much cleaner. How I do it is I create an extensions package in my code and create Kotlin files as so: ActivityExtensions.kt, FragmentExtensions.kt, and so on.

ActivityExtensions.kt

import android.support.v7.app.AppCompatActivity
import android.widget.Toast

public fun AppCompatActivity.displayQuickToast(message : String) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

public fun AppCompatActivity.displayLongToast(message : String) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

MainActivity.kt

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        displayLongToast("battery will die soon")
        displayLongToast("charging")
    }
}