Kotlin常见方法总结

joinToString

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, ...!

集合

一、listOf()函数

创建一个不可变的List

fun <T> listOf(): List<T>:返回空的list
fun <T> listOf(T): List<T>:返回只含有一个元素的list
fun <T> listOf(vararg T): List<T>:可变参数

二、mutableListOf()函数

创建可变的List
val list = mutableListOf(“Hello”, “World”)

三、arrayListOf()函数

创建可变的ArrayList

四、listOfNotNull()函数

以上的函数都是可以接受null作为元素的,这与Java中的List是不同的。而这个方法会把null全部剔除掉,返回包含所有非null值的List:

五、binarySearch()函数

Collections.kt文件中提供了四个针对List的binarySearch()函数,它们可以对列表进行二分查找:

fun <T> List<T>.binarySearch(element: T, comparator: Comparator<in T>, fromIndex: Int = 0, toIndex: Int = size): Int
fun <T> List<T>.binarySearch(fromIndex: Int = 0, toIndex: Int = size, comparison: (T) -> Int): Int
fun <T: Comparable<T>> List<T?>.binarySearch(element: T?, fromIndex: Int = 0, toIndex: Int = size): Int

inline fun <T, K : Comparable<K>> List<T>.binarySearchBy(key: K?, fromIndex: Int = 0, toIndex: Int = size, crossinline selector: (T) -> K?): Int 
    = binarySearch(fromIndex, toIndex) { compareValues(selector(it), key) }

高频使用的kotlin方言

Default values for function parameters 函数的默认值

fun foo(a: Int = 0, b: String = "") { ... }

Filtering a list 过滤一个集合

val positives = list.filter { x -> x > 0 }
   或者 val positives = list.filter { it > 0 }

String Interpolation 字符串插入

println("Name $name")

Instance Checks 实例检查

when (x) {
 is Foo -> ...
  is Bar -> ...
   else -> ...
    }

打印map集合

  for ((k, v) in map) { println("$k -> $v") }

遍历的时候使用range

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) { ... }

Read-only list:只读列表

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

Extension Functions:拓展方法

fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()

Creating a singleton:创建单例

object Resource {
    val name = "Name"
}

If not null shorthand

val files = File("Test").listFiles()
println(files?.size)

If not null and else shorthand

val files = File("Test").listFiles()
println(files?.size ?: "empty")

Executing a statement if null

val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")

Execute if not null

val data = ...
data?.let {
    ... // execute this block if not null
}

Return on when statement

fun transform(color: String): Int {
    return when (color) {
        "Red" -> 0
        "Green" -> 1
        "Blue" -> 2
        else -> throw IllegalArgumentException("Invalid color param value")
    }
}

‘try/catch’ expression

fun test() {
    val result = try {
        count()
    } catch (e: ArithmeticException) {
        throw IllegalStateException(e)
    }

    // Working with result
}

‘if’ expression

fun foo(param: Int) {
    val result = if (param == 1) {
        "one"
    } else if (param == 2) {
        "two"
    } else {
        "three"
    }
}

Builder-style usage of methods that return Unit

fun arrayOfMinusOnes(size: Int): IntArray {
    return IntArray(size).apply { fill(-1) }
}

Single-expression functions

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")
 }

Calling multiple methods on an object instance (‘with’)

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() 
}

Java 7’s try with resources

val stream = Files.newInputStream(Paths.get("/some/file.txt")) 
stream.buffered().reader().use { reader -> println(reader.readText()) }

对于需要泛型类型信息的通用函数的方便形式

// public final class Gson { 
// ... // public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
// ...
inline fun <reified T: Any> Gson.fromJson(json): T = this.fromJson(json, T::class.java)

Consuming a nullable Boolean

val b: Boolean? = ...
if (b == true) {
    ...
} else {
    // `b` is false or null
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值