Menu
Coddy logo textTech

ReadLine Input

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 37 of 93.

So far, your programs have used hardcoded values. To make programs interactive, you need to accept input from users. Kotlin provides the readLine() function for this purpose.

The readLine() function reads a line of text that the user types and returns it as a string:

fun main() {
    println("What is your name?")
    val name = readLine()
    println("Hello, $name!")
}

When this program runs, it prints the question, waits for the user to type something and press Enter, then uses that input in the greeting.

There's one important detail: readLine() returns a String? (nullable String) because the input could potentially be null. For now, you can use the !! operator to assert that the input won't be null:

fun main() {
    println("Enter your city:")
    val city = readLine()!!
    println("You live in $city")
}

The !! tells Kotlin you're confident the value won't be null, giving you a regular String to work with. This is fine for simple programs where you expect valid input.

challenge icon

Challenge

Easy

Read a person's firstName and lastName using readLine()!!, then print a welcome message.

You will receive two inputs:

  • First input: the person's first name
  • Second input: the person's last name

Print the following message using string templates:

Welcome, [firstName] [lastName]!

For example, if the inputs are John and Doe, the output should be:

Welcome, John Doe!

Try it yourself

fun main() {
    // Read the first name
    val firstName = readLine()!!
    
    // Read the last name
    val lastName = readLine()!!
    
    // TODO: Write your code below to print the welcome message using string templates
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground