kotlin
Today we will learn how to use Kotlin print functions and how to get and parse user input from console. Furthermore, we’ll look into Kotlin REPL.
今天,我们将学习如何使用Kotlin打印功能以及如何从控制台获取和解析用户输入。 此外,我们将研究Kotlin REPL。
Kotlin打印功能 (Kotlin Print Functions)
To output something on the screen the following two methods are used:
要在屏幕上输出某些内容,请使用以下两种方法:
- print() 打印()
- println() println()
The print
statement prints everything inside it onto the screen.
print
语句将其中的所有内容print
到屏幕上。
The println
statement appends a newline at the end of the output.
println
语句在输出末尾添加换行符。
The print statements internally call System.out.print
.
打印语句内部调用System.out.print
。
The following code shows print statements in action:
以下代码显示了运行中的打印语句:
fun main(args: Array<String>) {
var x = 5
print(x++)
println("Hello World")
print("Do dinasours still exist?\n")
print(false)
print("\nx is $x.")
println(" x Got Updated!!")
print("Is x equal to 6?: ${x == 6}\n")
}
To print a variable inside the print statement, we need to use the dollar symbol($) followed by the var/val name inside a double quoted string literal.
要在print语句中打印变量,我们需要在双引号字符串文字中使用美元符号($),后跟var / val名称。
To print the result of an expression we use ${ //expression goes here }
.
要打印表达式的结果,我们使用${ //expression goes here }
。
The output when the above code is run on the Kotlin Online Compiler is given below.
下面是在Kotlin在线编译器上运行上述代码时的输出。
转义文字和表达式 (Escape literals and expressions)
To escape the dollar symbol and let’s say treat ${expression} as a string only rather than calculating it, we can escape it.
要转义美元符号,并且说将$ {expression}仅当作字符串而不是对其进行计算,我们可以对其进行转义。
fun main(args: Array<String>) {
val y = "\${2 == 5}"
println("y = ${y}")
println("Do we use $ to get variables in Python or PHP? Example: ${'$'}x and ${'$'}y")
val z = 5
var str = "$z"
println("z is $str")
str = "\$z"
println("str is $str")
}
Note a simple $
without any expression/variable set against it implicitly escapes it and treats it as a part of the string only.
请注意,一个没有任何表达式/变量集的简单$
隐式地对其进行转义,并将其仅视为字符串的一部分。
打印功能值 (Printing function values)
fun sumOfTwo(a: Int, b: Int) : Int{
return a + b
}
fun main(args: Array<String>) {
val a = 2
val b = 3
println("Value of ${'$'}a and ${'$'}b is : ${sumOfTwo(a,b)}")
println(println("Printing Value of ${'$'}a and ${'$'}b is : ${sumOfTwo(a,b)}"))
}
The following output is printed:

打印以下输出:
Note: Passing a print inside another behaves like recursion. The innermost is printed first. print statement returns a Unit
(equivalent of void in Java).
注意:在另一个内部传递打印的行为类似于递归。 最里面的被首先打印。 print语句返回一个Unit
(相当于Java中的void)。
Kotlin用户输入 (Kotlin User Input)
To get the user input, the following two methods can be used:
要获取用户输入,可以使用以下两种方法:
Note: User input requires a command line tool. You can either use REPL or IntelliJ. Let’s use IntelliJ here.
注意:用户输入需要命令行工具。 您可以使用REPL或IntelliJ。 让我们在这里使用IntelliJ。
使用readLine() (Using readLine())
readLine()
returns the value of the type String? in order to deal with null values that can happen when you read the end of file etc.
readLine()
返回字符串类型的值? 为了处理在读取文件末尾等时可能发生的空值。
The following code shows an example using readLine()
以下代码显示了使用readLine()
的示例
fun main(args: Array<String>) {
println("Enter your name:")
var name = readLine()
print("Length is ${name?.length}")
}
As you can see we need to unwrap the nullable type to use the String type functions on the property.
Use a !! to force convert the String? to String, only when you’re absolutely sure that the value won’t be a null. Else it’ll crash.
如您所见,我们需要打开可空类型以在属性上使用String类型函数。
用一个 !! 强制转换字符串? 字符串,只有在您完全确定该值不会为null时。 否则它将崩溃。
Converting the input to an Integer
To convert the input String to an Int we do the following:
将输入转换为整数
要将输入String转换为Int,请执行以下操作:
fun main(args: Array<String>) {
var number = readLine()
try {
println("Number multiply by 5 is ${number?.toInt()?.times(5)}")
} catch (ex: NumberFormatException) {
println("Number not valid")
}
}
Again we use the ?.
operator to convert the nullable type to first an Int using toInt()
. Then we multiply it by 5.
同样,我们使用?.
运算符,使用toInt()
将可空类型首先转换为Int。 然后我们乘以5。
Reading Input continuously
We can use the do while loop to read the input continuously as shown below.
连续读取输入
我们可以使用do while循环来连续读取输入,如下所示。
do {
line = readLine()
if (line == "quit") {
println("Closing Program")
break
}
println("Echo $line")
} while (true)
}
The output of the above in the IntelliJ Command Line is given below.

下面是IntelliJ命令行中上述内容的输出。
使用拆分运算符读取多个值 (Reading Multiple Values using split operator)
We can read multiple values separated by delimiters and save them in a tuple form as shown below.
我们可以读取多个由定界符分隔的值,并将它们保存为元组形式,如下所示。
fun readIntegers(separator: Char = ',')
= readLine()!!.split(separator).map(String::toInt)
fun main(args: Array<String>) {
println("Enter your values:")
try {
val (a, b, c) = readLine()!!.split(' ')
println("Values are $a $b and $c")
} catch (ex: IndexOutOfBoundsException) {
println("Invalid. Missing values")
}
try {
val (x, y, z) = readIntegers()
println("x is $x y is $y z is $z")
} catch (ex: IndexOutOfBoundsException) {
println("Invalid. Missing values")
}
catch (ex: NumberFormatException) {
println("Number not valid")
}
}
The split
function takes in the character that’ll be the delimiter.
readIntegers()
function uses a map on a split to convert each value to an Int.
If you enter values lesser than the specified in the tuple, you’ll get an IndexOutOfBoundsException.
We’ve used try-catch in both the inputs.
split
函数接受将成为定界符的字符。
readIntegers()
函数使用拆分上的映射将每个值转换为Int。
如果输入的值小于元组中指定的值,则将获得IndexOutOfBoundsException。
我们在两个输入中都使用了try-catch。
The output looks like this:

输出看起来像这样:
Alternatively, instead of tuples, we can use a list too as shown below.
另外,代替元组,我们也可以使用列表,如下所示。
val ints: List<String>? = readLine()?.split("|".toRegex())
println(ints)
Kotlin扫描器类别 (Kotlin Scanner Class)
To take inputs we can use Scanner(System.`in`)
which takes inputs from the standard input keyboard.
The following code demonstrates the same:
要接受输入,我们可以使用Scanner(System.`in`)
从标准输入键盘接受输入。
以下代码演示了相同的内容:
fun main(args: Array<String>) {
val reader = Scanner(System.`in`)
print("Enter a number: ")
// nextInt() reads the next integer. next() reads the String
var integer:Int = reader.nextInt()
println("You entered: $integer")
reader.nextInt()
reads the next integer.
reader.nextInt()
读取下一个整数。
reader.next()
reads the next String. reader.nextFloat() reads the next float and so on.
reader.next()
读取下一个String。 reader.nextFloat()读取下一个浮点数,依此类推。
reader.nextLine()
passes the Scanner to the nextLine and also clears the buffer.
reader.nextLine()
将扫描程序传递到nextLine并清除缓冲区。
The following code demonstrates reading different types of inputs inside a print statement directly.
以下代码演示了如何直接在print语句中读取不同类型的输入。
import java.util.*
fun main(args: Array<String>) {
val reader = Scanner(System.`in`)
print("Enter a number: ")
try {
var integer: Int = reader.nextInt()
println("You entered: $integer")
} catch (ex: InputMismatchException) {
println("Enter valid number")
}
enterValues(reader)
//move scanner to next line else the buffered input would be read for the next here only.
reader.nextLine()
enterValues(reader)
}
fun enterValues(reader: Scanner) {
println("Enter a float/boolean :")
try {
print("Values: ${reader.nextFloat()}, ${reader.nextBoolean()}")
} catch (ex: InputMismatchException) {
println("First value should be a float, second should be a boolean. (Separated by enter key)")
}
}
InputMismatchException is thrown when the input is of a different type from the one asked.
当输入的类型与要求的类型不同时,将引发InputMismatchException。
The output is given below.

输出如下。
Kotlin REPL (Kotlin REPL)
REPL also known as Read-Eval-Print-Loop is used to run a part of code in an interactive shell directly.
W
e can do so in our terminal/command line by initiating the kotlin compiler.
REPL也称为Read-Eval-Print-Loop,用于直接在交互式shell中运行部分代码。
w ^
您可以通过启动kotlin编译器在终端/命令行中执行此操作。
安装命令行编译器 (Installing the Command Line Compiler)
We can install command line compiler on Mac/Windows/Ubuntu as demonstrated here.
我们可以证明在Mac / Windows的/ Ubuntu的安装命令行编译器在这里 。
Typically, on a mac, we can use HomeBrew on our terminal to install the kotlin compiler.
通常,在Mac上,我们可以在终端上使用HomeBrew来安装kotlin编译器。
brew update
brew install kotlin
Once it is done, start the REPL by entering kotlinc
in your terminal/cmd
Following is my first code in the REPL.

完成后,通过在终端/ cmd中输入kotlinc
启动REPL
以下是我在REPL中的第一个代码。
That’s all for Kotlin print functions and quick introduction of Kotlin REPL.
这就是Kotlin打印功能和Kotlin REPL的快速介绍。
翻译自: https://www.journaldev.com/19757/kotlin-print-println-readline-scanner-repl
kotlin