赞
踩
fun test1() { //1 创建Set val set = hashSetOf(1, 7, 53) //2 创建list val list = arrayListOf(1, 7, 53) //3 创建map val map = hashMapOf(1 to "one", 7 to "seven", 53 to "fifty-three") println("set.javaClass = " + set.javaClass) println("list.javaClass = " + list.javaClass) println("map.javaClass = " + map.javaClass) //4 获取列表中的最后一个元素 val strings = listOf("first", "second", "fourteenth") println("strings.last() = " + strings.last()) val numbers = setOf(1, 14, 2) println("numbers.max() = " + numbers.max()) }
输出结果
set.javaClass = class java.util.HashSet
list.javaClass = class java.util.ArrayList
map.javaClass = class java.util.HashMap
strings.last() = fourteenth
numbers.max() = 14
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() }
fun test2() {
//1 打印集合
val list = listOf(1, 2, 3)
println("list = " + list)
//2 自定义输出格式
println(joinToString(list, "; ", "(", ")"))
}
list = [1, 2, 3]
(1; 2; 3)
fun test3() {
//1 显示标明参数名称,避免混淆
val list = listOf(1, 2, 3)
joinToString(list, separator = "", prefix = "", postFix = "")
}
fun defaultValue(string1: String, string2: String = "", string3: String = "") {
println("string1 = " + string1 + ", string2 = " + string2 + ", string3 = " + string3)
}
fun test4() {
defaultValue("1")
defaultValue("1", "2")
defaultValue("1", "2", "3")
}
string1 = 1, string2 = , string3 =
string1 = 1, string2 = 2, string3 =
string1 = 1, string2 = 2, string3 = 3
//修改文件类名
@file:JvmName("StringFunctions")
package com.yl.lib.kt.chapter_2
fun joinToStringTest(): String {
return "null"
}
var opCount = 0
fun performOperation() {
opCount++
}
fun String.lastChar(): Char = this.get(this.length - 1)
public static void test5() {
//1 顶层函数 不添加修改文件名的声明时
//JoinKt.joinToStringTest();
//2 修改文件类名 @file:JvmName("StringFunctions")
StringFunctions.joinToStringTest();
//3 顶层属性
for (int i = 0; i < 5; i++) {
StringFunctions.performOperation();
}
System.out.println("StringFunctions.opCount = " + StringFunctions.getOpCount());
}
输出结果
StringFunctions.opCount = 5
//导入函数
import com.yl.lib.kt.chapter_2.lastChar
fun test5() {
println("Kotlin".lastChar())
}
public static void test6(){
char c = StringFunctions.lastChar("Java");
System.out.println("c = " + c);
}
输出结果
c = a
fun test6() {
var list = listOf(1, 2, 3)
println(list.joinToStringTest(separator = ";", prefix = "(", postfix = ")"))
}
(1;2;3)
//1 重写成员函数
open class View {
open fun click() = println("View clicked")
}
class Button : View() {
override fun click() = println("Button clicked")
}
fun test7() {
val view: View = Button()
view.click()
}
输出结果
Button clicked
//1 此处的扩展函数会编译成静态函数,所以不能重写
//2 此处的扩展函数声明在类的外部
fun View.showOff() = println("I'm a view!")
fun Button.showOff() = println("I'm a button!")
fun test8() {
val view: View = Button()
view.showOff()
}
输出结果
I'm a view!
//1 声明一个扩展属性 val String.lastChar1: Char get() = get(length - 1) //2 声明一个可变的扩展属性 var StringBuilder.lastChar2: Char get() = get(length - 1) set(value: Char) { this.setCharAt(length - 1, value) } fun test9() { println("kotlin.lastChar1 = " + "kotlin".lastChar1) val sb = StringBuilder("Kotlin?") sb.lastChar2 = '!' println(sb) }
输出结果
kotlin.lastChar1 = n
Kotlin!
fun test10() {
val strings: List<String> = listOf("first", "second", "fourteenth")
println("strings.last() = " + strings.last())
var numbers: Collection<Int> = setOf(1, 14, 2)
println("numbers.max() = " + numbers.max())
}
输出结果
strings.last() = fourteenth
numbers.max() = 14
fun test11() {
// list of支持可变参数,使用vararg修复符
val list = listOf(2, 3, 5, 7, 11)
}
fun test12() { //1 这行代码中的 to 不是内置的结构,而是一种特殊的函数调用,被称为中缀调用 val map = mapOf(1 to "one", 7 to "seven", 53 to "fifty-three", 2.to("two")) //2 中缀调用 没有添加额外的分隔符, 函数名称是直接放在目标对象名称和参数之前 //3 2.to("two") 等价于 2 to "two" //4 要允许使用中缀符号调用函数, 需要使用infix修饰符来标记它 // infix fun Any.to(other:Any) = Pair<this, Other> //5 可以直接用Pair来初始化两个变量 这个功能称为解构声明 val (numver, name) = 1 to "one" //6 解构声明也适用于循环 val collection: Collection<String> = arrayListOf("one", "two", "three") for ((index, element) in collection.withIndex()) { println("$index: $element") } }
输出结果
0: one
1: two
2: three
fun test13() {
var splitStr1 = "12.345-6.A".split("\\.|-".toRegex())
println("splitStr1 = " + splitStr1)
var splitStr2 = "12.345-6.A".split(".", "-")
println("splitStr2 = " + splitStr2)
}
splitStr1 = [12, 345, 6, A]
splitStr2 = [12, 345, 6, A]
//1 使用String的扩展函数来解析文件路径 fun parsePath1(path: String) { val directory = path.substringBeforeLast("/") val fullName = path.substringAfterLast("/") val fileName = fullName.substringBeforeLast(".") val extension = fullName.substringAfterLast(".") println("Dir: $directory, name: $fileName, ext $extension") } //2 使用正则表达式解析文件路径 fun parsePath2(path: String) { val regex = """(.+)/(.+)\.(.+)""".toRegex() val matchResult = regex.matchEntire(path) if (matchResult != null) { val (directory, filename, extension) = matchResult.destructured println("Dir:$directory, name:$filename, ext:$extension") } } fun test14() { parsePath1("/Users/yole/kotlin-book/chapter.adoc") parsePath2("/Users/yole/kotlin-book/chapter.adoc") }
输出结果
Dir: /Users/yole/kotlin-book, name: chapter, ext adoc
Dir:/Users/yole/kotlin-book, name:chapter, ext:adoc
//1 带重复代码的函数
class User(val id:Int, val name:String, val address:String)
fun saveUser1(user:User){
if(user.name.isEmpty()){
throw IllegalArgumentException("Can't save user ${user.id}:empty Name")
}
if(user.address.isEmpty()){
throw IllegalArgumentException("Can't save user${user.id}:empty Address")
}
}
Exception in thread "main" java.lang.IllegalArgumentException: Can't save user 1:empty Name
at com.yl.lib.kt.chapter_3.Chapter3TestKt.saveUser1(Chapter3Test.kt:264)
//2 提取局部函数来避免重复
fun saveUser2(user:User){
fun validate(user:User, value:String, fieldName:String){
if(value.isEmpty()){
throw IllegalArgumentException("Can't save user ${user.id} empty $fieldName")
}
}
validate(user, user.name, "Name")
validate(user, user.address, "Address")
}
Exception in thread "main" java.lang.IllegalArgumentException: Can't save user 1 empty Name
at com.yl.lib.kt.chapter_3.Chapter3TestKt$saveUser2$1.invoke(Chapter3Test.kt:279)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。