fun main(args: Array<String>) {
println("Hello, world!")
}
var
的内容来自变量。它可以随时改变。
var answer = 12
answer = 13 // 编译通过
val
的内容来自值。初始化之后不能改变。
val age = 18
age = 19 // 编译错误
整数类型:val answer: Int = 42
浮点类型:val yearsToCompute = 7.5e6
字符类型: val question = "The Ultimate Question of Life, the Universe, and Everything"
字符串模板
val $name = 'world'
println("Hello, $name!")
大括号内可以是kotlin表达式
fun main(args: Array<String>) {
if (args.size > 0) {
println("Hello, ${args[0]}!")
}
println("Hello, ${if (args.size > 0) args[0] else "someone"}!")
}
常规定义
fun max(a: Int, b: Int): Int {
return if (a > b) a else b
}
把函数当成表达式
fun max(a: Int, b: Int): Int = if (a > b) a else b
使用命名参数
fun <T> joinToString(
collection: Collection<T>,
separator: String,
prefix: String,
postfix: String
): String {
val result = StringBuilder(prefix)
for ((index, element) in collection.withIndex()) {
if (index > 0) result.append(separator)
result.append(element)
}
result.append(postfix)
return result.toString()
}
joinToString(collection, separator = " ", prefix = " ", postfix = ".")
使用参数默认值
>>> val list = listOf(1, 2, 3)
>>> println(list)
[1, 2, 3]
fun <T> joinToString(
collection: Collection<T>,
separator: String = ", ",
prefix: String = "",
postfix: String = ""
): String {
val result = StringBuilder(prefix)
for ((index, element) in collection.withIndex()) {
if (index > 0) result.append(separator)
result.append(element)
}
result.append(postfix)
return result.toString()
}
>>> joinToString(list, ", ", "", "")
1, 2, 3
>>> joinToString(list)
1, 2, 3
>>> joinToString(list, "; ")
1; 2; 3
fun readNumber(reader: BufferedReader): Int? {
try {
val line = reader.readLine()
return Integer.parseInt(line)
}
catch (e: NumberFormatException) {
return null
}
finally {
reader.close()
}
}
enum class Color {
RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET
}
Kotlin in action 一书的中文翻译
更方便的阅读模式请移步gitbook项目
ebook目录下是原文原版电子书和书中源码
亲,如果你觉得这个项目不错,请为我star一下~
ebook store in ebook
directory, download or star is welcomed