Book Image

Kotlin Programming Cookbook

By : Aanand Shekhar Roy, Rashi Karanpuria
Book Image

Kotlin Programming Cookbook

By: Aanand Shekhar Roy, Rashi Karanpuria

Overview of this book

The Android team has announced first-class support for Kotlin 1.1. This acts as an added boost to the language and more and more developers are now looking at Kotlin for their application development. This recipe-based book will be your guide to learning the Kotlin programming language. The recipes in this book build from simple language concepts to more complex applications of the language. After the fundamentals of the language, you will learn how to apply the object-oriented programming features of Kotlin 1.1. Programming with Lambdas will show you how to use the functional power of Kotlin. This book has recipes that will get you started with Android programming with Kotlin 1.1, providing quick solutions to common problems encountered during Android app development. You will also be taken through recipes that will teach you microservice and concurrent programming with Kotlin. Going forward, you will learn to test and secure your applications with Kotlin. Finally, this book supplies recipes that will help you migrate your Java code to Kotlin and will help ensure that it's interoperable with Java.
Table of Contents (21 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Parsing String to Long, Double, or Int


Kotlin makes it really easy to parse String into other data types, such as Long, Integer, or Double.

In JAVA, Long.parseLong(), or the Long.valueOf() static method is used, which parses the string argument as a signed decimal long and returns a long value, and similarly for other data types such as Int, Double, and Boolean. Let’s see how to achieve it in Kotlin.

Getting ready

You just need a Kotlin editor to write and run your code. We’ll use conversion of Long as an example to discuss parsing with string. Conversion to other data types is quite similar.

How to do it...

To parse the string to a Long data type, we use the .toLong() method with the string. It parses the string as a Long number and returns the result. It throws NumberFormatException if the string is not a valid representation of a number. Later, we will see examples for this.

Converting String to Long

Here's an example that shows parsing of string to Long:

fun main(args: Array<String>) {
  val str="123"
  print(str.toLong())
}

When you run the preceding code, you will see this output:

123

If you don’t want to deal with the exceptions, you can use .toLongOrNull(). This method parses the string as a Long and returns the result, or null if the string is not a valid representation of a number.

Converting string to Long using string.toLongOrNull()

In this example, we will see how we can parse a string using the .toLongOrNull() method:

fun main(args: Array<String>) {
  val str="123.4"
  val str2="123"
  println(str.toLongOrNull())
  println(str2.toLongOrNull())
}

On running the preceding program, the following output is generated:

 null 123
Converting with special radix

All the preceding examples use the base (radix) 10. There are cases when we wish to convert a String to Long but using another base. Both string.toLong() and string.toLongOrNull() can receive a custom radix to be used in the conversion. Let's take a look at its implementation:

  • string.toLong(radix):
    • This 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
  • string.toLongOrNull(radix):
    • This 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

Parsing string to Long with special radix

In the preceding examples, we were parsing strings with radix 10, that is, decimals. By default, the radix is taken as 10, but there are certain situations where we need different radix. For example, in case of parsing a string into a binary or octal number. So now, we will see how to work with radix other than the decimal. Though you can use any valid radix, we will show examples that are most commonly used, such as binary and octal.

  • Binary: Since a binary number is made from 0 and 1, the radix used is 2:
fun main(args: Array<String>) {
       val str="11111111"
       print(str.toLongOrNull(2))   }

On running the preceding program, the following output is generated:

 255
  • Octal: The octal numeral system, or oct for short, is the base-8 number system and uses the digits 0 to 7. Hence, we will use 8 as a radix:
fun main(args: Array<String>) {
      val str="377"
       print(str.toLongOrNull(8))
   }

On running the preceding program, this output is generated:

 255
  • Decimal: The decimal system has 10 numbers in it (0-9); hence, we will use 10 as radix. Note that radix as 10 is used by default in the methods without the radix arguments (.toLong() , .toLongOrNull()):
fun main(args: Array<String>) {
      val str="255"
       print(str.toLongOrNull(10))
   }

On running the preceding program, the following output is generated:

 255

How it works...

Kotlin uses String’s extension functions such as .toLong() and toLongOrNull() to make things easier. Let’s dive into their implementation.

  • For Long, use this:
public inline fun String.toLong(): Long = java.lang.Long.parseLong(this)

As you can see, internally, it also calls the Long.parseLong(string) Java static method, and it is similar to the other data types.

  • For Short, it's the following:
public inline fun String.toShort(): Short = java.lang.Short.parseShort(this)
  • Use this for Int:
public inline fun String.toInt(): Int = java.lang.Integer.parseInt(this)
  • For parsing with Radix, use the following:
public inline fun String.toLong(radix: Int): Long = java.lang.Long.parseLong(this, checkRadix(radix))

The checkRadix method checks whether the given [radix] is valid radix for string to number and number to string conversion.

There's more...

Let’s quickly see a few other extension functions provided by Kotlin to parse String:

  • toBoolean(): Returns `true` if the content of this string is equal to the word true, ignoring case, and `false` otherwise.
  • toShort(): Parses the string as a [Short] number and returns the result. Also, it throws NumberFormatException if the string is not a valid representation of a number.
  • toShort(radix): Parses the string as a [Short] number and returns the result, throws NumberFormatException if the string is not a valid representation of a number, and throws IllegalArgumentException when [radix] is not a valid radix for the string to number conversion.
  • toInt(): Parses the string as an [Int] number and returns the result and throws NumberFormatException if the string is not a valid representation of a number.
  • toIntOrNull(): Parses the string as an [Int] number and returns the result or `null` if the string is not a valid representation of a number.
  • toIntOrNull(radix): Parses the string as an [Int] number and returns the result or `null` if the string is not a valid representation of a number, or @throws IllegalArgumentException when [radix] is not a valid radix for string to number conversion.
  • toFloat(): Parses the string as a [Float] number and returns the result, and @throws NumberFormatException if the string is not a valid representation of a number.
  • toDouble() : Parses the string as a [Double] number and returns the result, and @throws NumberFormatException if the string is not a valid representation of a number.