Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Kotlin Programming Cookbook

You're reading from   Kotlin Programming Cookbook Explore more than 100 recipes that show how to build robust mobile and web applications with Kotlin, Spring Boot, and Android

Arrow left icon
Product type Paperback
Published in Jan 2018
Publisher
ISBN-13 9781788472142
Length 434 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Aanand Shekhar Roy Aanand Shekhar Roy
Author Profile Icon Aanand Shekhar Roy
Aanand Shekhar Roy
Rashi Karanpuria Rashi Karanpuria
Author Profile Icon Rashi Karanpuria
Rashi Karanpuria
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Installation and Working with Environment FREE CHAPTER 2. Control Flow 3. Classes and Objects 4. Functions 5. Object-Oriented Programming 6. Collections Framework 7. Handling File Operations in Kotlin 8. Anko Commons and Extension Function 9. Anko Layouts 10. Databases and Dependency Injection 11. Networking and Concurrency 12. Lambdas and Delegates 13. Testing 14. Web Services with Kotlin 15. Other Books You May Enjoy

Reading console input in Kotlin

In many applications, user interaction is a very important part, and the most basic way of doing that is reading input entered by the user and giving output based on it. In this recipe, we will understand different ways of reading input and also provide output in the console.

Getting ready

You need to install a preferred development environment that compiles and runs Kotlin. You can also use the command line to compile and run your Kotlin code, for which you need Kotlin compiler installed along with JDK.

How to do it...

Let's go through the following steps by which we can read console input in Kotlin:

  1. We will start simple and move to more advanced logic as we move forward. First, let's start with simply printing a line as output in the console:
println("Just a line")
  1. Now we will try to take String input from the console and output it again:
println("Input your first name")
var first_name = readLine()
println("Your first name: $first_name")
  1. Okay, how about we repeat the process with Int:
println("Hi $first_name, let us have a quick math test. Enter two numbers separated by space.")
val (a, b) = readLine()!!.split(' ').map(String::toInt)
println("$a + $b = ${a+b}")
  1. Now, let's try a complicated code and then start with the explanations:
fun main(args: Array<String>) {
println("Input your first name")
var first_name = readLine()
println("Input your last name")
var last_name = readLine()
println("Hi $first_name $last_name, let us have a quick math test. Enter two numbers separated by space.")
val (a, b) = readLine()!!.split(' ').map(String::toInt)
println("what is $a + $b ?")
println("Your answer is ${if (readLine()!!.toInt() == (a+b)) "correct" else "incorrect"}")
println("Correct answer = ${a+b}")
println("what is $a * $b ?")
println("Your answer is ${if (readLine()!!.toInt() == (a*b)) "correct" else "incorrect"}")
println("Correct answer = ${a*b}")
println("Thanks for participating :)")
}

Here's a screenshot of compiling and running the preceding code:

How it works...

Let's try to understand the methods by which we were able to read input in Kotlin.

Behind the scenes, Kotlin.io uses java.io for the input-output. So println is basically System.out.println, but with additional power by Kotlin to use String templates and inline functions, which makes writing extremely simple and concise.

This is a part of the actual code from Kotlin stdlib used for Console IO:

/** Prints the given message and newline to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun println(message: Any?) {
System.out.println(message)
}
You have been reading a chapter from
Kotlin Programming Cookbook
Published in: Jan 2018
Publisher:
ISBN-13: 9781788472142
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image