How to convert String to Long in Kotlin?

Five different coding ways to  convert String to Long in Kotlin
06 September 2017   646

There are 5 different to convert String to Long in Kotlin programming language.

1. string.toLong()

Parses the string as a [Long] number and returns the result.
@throws NumberFormatException if the string is not a valid representation of a number.

2. string.toLongOrNull()

Parses the string as a [Long] number and returns the result or null if the string is not a valid representation of a number.

3. str.toLong(10)

Parses the string as a [Long] number and returns the result.
@throws NumberFormatException if the string is not a valid representation of a number.
@throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.

public inline fun String.toLong(radix: Int): Long = java.lang.Long.parseLong(this, checkRadix(radix))

4. string.toLongOrNull(10)

Parses the string as a [Long] number and returns the result or null if the string is not a valid representation of a number.
@throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.

public fun String.toLongOrNull(radix: Int): Long? {...}

5. java.lang.Long.valueOf(string)

public static Long valueOf(String s) throws NumberFormatException

 

How to convert list to map in Kotlin

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

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()