val numbers = listOf(1, 2, 3, 4, 5, 6)
println(numbers.joinToString()) // 1, 2, 3, 4, 5, 6
println(numbers.joinToString(prefix = "[", postfix = "]")) // [1, 2, 3, 4, 5, 6]
println(numbers.joinToString(prefix = "<", postfix = ">", separator = "•")) // <1•2•3•4•5•6>
val chars = charArrayOf('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q')
println(chars.joinToString(limit = 5, truncated = "...!") { it.toUpperCase().toString() }) // A, B, C, D, E, ...!
创建一个不可变的List
fun listOf(): List:返回空的list
fun listOf(T): List:返回只含有一个元素的list
fun listOf(vararg T): List:可变参数
创建可变的List
val list = mutableListOf(“Hello”, “World”)
创建可变的ArrayList
以上的函数都是可以接受null作为元素的,这与Java中的List是不同的。而这个方法会把null全部剔除掉,返回包含所有非null值的List:
Collections.kt文件中提供了四个针对List的binarySearch()函数,它们可以对列表进行二分查找:
fun List.binarySearch(element: T, comparator: Comparator, fromIndex: Int = 0, toIndex: Int = size): Int
fun List.binarySearch(fromIndex: Int = 0, toIndex: Int = size, comparison: (T) -> Int): Int
fun > List.binarySearch(element: T?, fromIndex: Int = 0, toIndex: Int = size): Int
inline fun > List.binarySearchBy(key: K?, fromIndex: Int = 0, toIndex: Int = size, crossinline selector: (T) -> K?): Int
= binarySearch(fromIndex, toIndex) { compareValues(selector(it), key) }
fun foo(a: Int = 0, b: String = "") { ... }
val positives = list.filter { x -> x > 0 }
或者 val positives = list.filter { it > 0 }
println("Name $name")
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
for ((k, v) in map) { println("$k -> $v") }
for (i in 1..100) { ... } // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }
val list = listOf("a", "b", "c")
Read-only map
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
Accessing a map
println(map["key"])
map["key"] = value
fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()
object Resource {
val name = "Name"
}
val files = File("Test").listFiles()
println(files?.size)
val files = File("Test").listFiles()
println(files?.size ?: "empty")
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
val data = ...
data?.let {
... // execute this block if not null
}
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// Working with result
}
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
fun theAnswer() = 42
This is equivalent to
fun theAnswer(): Int {
return 42
}
这能有效的和其他方言相结合,旨在更简洁的代码。例如when表达式
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}
val myTurtle = Turtle() with(myTurtle) { //画一个100像素的正方形
penDown()
for(i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader -> println(reader.readText()) }
// public final class Gson {
// ... // public T fromJson(JsonElement json, Class classOfT) throws JsonSyntaxException {
// ...
inline fun Gson.fromJson(json): T = this.fromJson(json, T::class.java)
val b: Boolean? = ...
if (b == true) {
...
} else {
// `b` is false or null
}