Java static methods in Kotlin

 The best way to represent a static Java method in Kotlin
11 September 2017   588

You can place the function in the "companion object"

So the java code like this:

class Foo { public static int a() { return 1; } }

will become

class Foo { companion object { fun a() : Int = 1 } }

What is Companion Objects?

An object declaration inside a class can be marked with the companion keyword:

class MyClass {
   companion object Factory {
       fun create(): MyClass = MyClass()
   }
}

Members of the companion object can be called by using simply the class name as the qualifier:

val instance = MyClass.create()

However, on the JVM you can have members of companion objects generated as real static methods and fields, if you use the @JvmStatic annotation. See the Java interoperability section for more details.

How to convert list to map in Kotlin

Two ways to convert list to map in Kotlin, with code examples
31 October 2017   516

For example, you have a list of strings like:

val list = listOf("a", "b", "c", "d")

and you need to convert it to a map, where the strings are the keys.

There are two ways to do this:

The first and most performant is to use associateBy function that takes two lambdas for generating the key and value, and inlines the creation of the map:

val map = friends.associateBy({it.facebookId}, {it.points})

The second, less performant, is to use the standard map function to create a list of Pair which can be used by toMap to generate the final map:

val map = friends.map { it.facebookId to it.points }.toMap()