-
Notifications
You must be signed in to change notification settings - Fork 146
/
KotlinTip4.kt
54 lines (49 loc) · 1.2 KB
/
KotlinTip4.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.sw.kotlin.tip4
/*
* 扩展函数
* */
fun String.lastChar(): Char = this.get(this.length - 1)
fun testFunExtension() {
val str = "test extension fun";
println(str.lastChar())
}
/*
* 用扩展函数改造Tip3中的列表打印内容函数
* */
fun <T> Collection<T>.joinToString3(separator: String = ", ",
prefix: String = "",
postfix: String = ""): String {
val result = StringBuilder(prefix)
for ((index, element) in withIndex()) {
if (index > 0) result.append(separator)
result.append(element)
}
result.append(postfix)
return result.toString()
}
fun printList4() {
val list = listOf(2, 4, 0)
println(list.joinToString3("/"))
}
/*
* 扩展属性 lastChar获取String的最后一个字符
* */
val String.lastChar: Char
get() = get(length - 1)
/*
* 扩展属性 lastChar获取StringBuilder的最后一个字符
* */
var StringBuilder.lastChar: Char
get() = get(length - 1)
set(value: Char) {
setCharAt(length - 1, value)
}
/*
* 测试
* */
fun testExtension(){
val s = "abc"
println(s.lastChar)
val sb = StringBuilder("abc")
println(sb.lastChar)
}