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
EasyRead 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
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground