Kotlin Input/Output & Comments

You will learn how to take input from user and display output to the screen in kotlin language using this post. You can also learn how to use comments in kotlin. Comments are used to provide information about each line to understand code to other programmers. Comments do not execute by compiler.

Kotlin Output

It is performed by using two methods print() and println(). print() method is used to print string inside the method “()”. println() method is used to print string similar like print(). Then the cursor moves line to beginning of next line.
 fun main(args: Array<String>) {
    println("1");
    println("hi");
    print("2");
    print("hello");
}
Output:
1
hi    
2hello

Kotlin Input

To take input from user, we use readLine() function which is used to read line from standard input stream.
fun main(args: Array<String>) {
    println("Enter a number between 10 and 30");
    val enteredNum = readLine()
    print("Your number is $enteredNum");
}
Output:
Enter a number between 10 and 30
25
Your number is 25
readLine() function explicitly converts string to values of other datatypes if you want. For this you need to use Scanner object from java library. For example getting integer input from user
fun main(args: Array<String>) {
    val read = Scanner(System.`in`)  
    println("Enter your age")  
    var age = read.nextInt()  
    println("Your age is "+age) 
}
Output:
Enter your age
25
Your age is 25

Kotlin Comments

There are two types of comments: Single line and Multi line
Single line comment:
It is used to comment single line and it is displayed by “//“.
fun main(args: Array<String>) {  
    // print Hello World text   
    println("Hello World")  
}  
Multi line Comment:
It is used to comment multiple lines and it is displayed by “/* */“.
fun main(args: Array<String>) {  
/* this statement 
   is used 
   for print */  
   println("Hello World")  
}  

Leave a Reply