Kotlin学习笔记 第一阶段 基本介绍
Kotlin成为Android的第一语言
Kotlin语言编译后产生字节码,JVM产生指令对,操作系统进行命令式的执行
Kotlin集聚各个语言的精华于一身,走全栈语言之路
val只读变量
1 2 3 4 5 6 7 val a:String = "111" println(a)
var可变变量
1 2 3 4 5 6 var a:String = "111" a = "222" println(a)
Java语言有两种数据类型,基本数据类型(int,double等等)和引用类型(String)
Kotlin语言只有一种数据类型,看起来都是引用类型,实际上,编译器会在Java字节码中修改为基本类型
查看字节码
range表达式
1 2 3 4 5 6 7 8 9 10 11 12 13 val number = 80 if (number in 10. .100 ) { println("在10到100" ) } else if (number in 0. .9 ) { println("在0到9" ) } else { println("大于100" ) }
when表达式
相当于Java中的switch
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 val week = 7 val info = when (week) { 1 -> "今天是星期一" 2 -> "今天是星期一" 3 -> "今天是星期一" 4 -> "今天是星期一" 5 -> "今天是星期一" else -> { "今天是周末" } } println(info)
String模板
1 2 3 4 5 6 7 8 9 10 11 12 val time = 5 val garden = "中山公园" println("今天天气晴朗,是星期$time ,去${garden} 玩" ) val isLogin = true println("用户登录结果为:${if (isLogin) "登录成功" else "登录失败" } " )
函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 private fun method (age: Int , name: String ) : Int { println("年龄为$age ,姓名为$name " ) return 200 }
函数参数的默认参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 fun main (args: Array <String >) { action01("wangwu" ,30 ) action02("wangwu" ) action03() } private fun action01 (name:String ,age: Int ) { println("名字为$name ,年龄为$age " ) } private fun action02 (name:String ,age: Int =77 ) { println("名字为$name ,年龄为$age " ) } private fun action03 (name:String ="Wangwu" ,age: Int =77 ) { println("名字为$name ,年龄为$age " ) }
具名函数参数
1 2 3 4 5 6 7 8 fun main (args: Array <String >) { login(username = "111" , password = "222" , age = 22 , phoneNumber = "12345" ) } private fun login (username:String ,password:String ,phoneNumber:String ,age:Int ) { println("成功" ) }
Nothing类型特点
1 2 3 4 5 6 7 8 9 10 11 12 fun main (args: Array <String >) { show(-1 ) } private fun show (number: Int ) { when (number) { -1 -> TODO("没有这个分数" ) in 0. .59 -> println("不及格" ) in 60. .70 -> println("成绩还可以" ) } }
反引号中函数名的特点
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 fun main (args: Array <String >) { 测试环境测试("111" ,"222" ) Test.`in `() `5553343 `() } private fun `测试环境测试`(username:String ,password:String ) { println("username:$username ,password:$password " ) } private fun `5553343`() { }
第二阶段 匿名函数
1 2 3 4 5 6 7 8 9 10 11 fun main () { val len = "Test" .count { it == 'e' } println(len) }
函数类型和隐式返回
匿名函数的声明和实现以及调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 //1.函数输入输出的声明 val test: () -> String //2.对上面函数的实现 test = { //这里的括号内的内容相当于下面的return部分的内容 //注意匿名函数不要写return,最后一行就是返回值 val tt = "66" "test$tt" //这里隐式返回,并且自动推断返回类型是否正确,这里返回int类型就会报错 } //3.调用函数 println(test()) /** * 上面大致等价于下面 * fun test():String{ * return "test" * } */
函数参数
匿名函数简洁写法,并且需要传入参数
1 2 3 4 5 6 7 8 9 10 val test: (Int , Int , Int ) -> String = { num1, num2, num3 -> val tt = "传入参数内容如下:" println("${tt} num1:${num1} ,num2:${num2} ,num3:${num3} " ) "${tt} num1:${num1} ,num2:${num2} ,num3:${num3} " } test.invoke(1 , 2 , 3 ) test(1 , 2 , 3 )
it关键字的特点
匿名函数中的it关键字
1 2 3 4 5 //匿名函数是只有一个入参,就有一个it val test2: (String) -> String = { "自带一个it,为传入的内容,为$it" } println(test2("111"))
匿名函数的类型推断
如果不能推断出唯一的类型,那么就推断为Any
1 2 3 4 5 6 7 8 val method1 = { val1: Double , val2: Float , val3: String -> "传入参数分别为:$val1 ,$val2 ,$val3 " } println(method1(1.34 ,123f ,"1da" ))
lambda
匿名函数其实就是lambda表达式
函数定义参数是函数的函数
在Java中可以通过接口来实现,在kotlin可以更加简单地实现
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 fun main () { loginAction("wuleizhenshang" , "10086" ) { msg: String, code: Int -> println("登录情况如下:$msg ,$code " ) } loginAction("wuleizhenshang" , "10086" ,{ msg: String, code: Int -> println("登录情况如下:$msg ,$code " ) }) loginAction("wuleizhenshang" , "10086" , responseResult = { msg: String, code: Int -> println("登录情况如下:$msg ,$code " ) }) } const val USER_NAME_DB = "wuleizhenshang" const val USER_PWD_DB = "10086" fun loginAction (username: String , password: String , responseResult: (String , Int ) -> Unit ) { if (username == null || password == null ) { TODO("用户名或密码为空" ) } if (username.length > 3 && password.length > 3 ) { if (webServiceLoginApi(username, password)) { responseResult("login success" , 200 ) } else { responseResult("login fail" , 404 ) } } else { TODO("用户名或密码不合格" ) } } private fun webServiceLoginApi (username: String , password: String ) : Boolean { return username == USER_NAME_DB && password == USER_PWD_DB }
内联学习
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 55 56 package s2fun main () { loginAction("wuleizhenshang" , "10086" ) { msg: String, code: Int -> println("登录情况如下:$msg ,$code " ) } loginAction("wuleizhenshang" , "10086" , { msg: String, code: Int -> println("登录情况如下:$msg ,$code " ) }) loginAction("wuleizhenshang" , "10086" , responseResult = { msg: String, code: Int -> println("登录情况如下:$msg ,$code " ) }) } const val USER_NAME_DB = "wuleizhenshang" const val USER_PWD_DB = "10086" inline fun loginAction (username: String , password: String , responseResult: (String , Int ) -> Unit ) { if (username == null || password == null ) { TODO("用户名或密码为空" ) } if (username.length > 3 && password.length > 3 ) { if (webServiceLoginApi(username, password)) { responseResult("login success" , 200 ) } else { responseResult("login fail" , 404 ) } } else { TODO("用户名或密码不合格" ) } } fun webServiceLoginApi (username: String , password: String ) : Boolean { return username == USER_NAME_DB && password == USER_PWD_DB }
不使用内联转换成Java如下
使用内联转换成Java如下
函数引用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 const val USER_NAME = "wuleizhenshang" const val USER_PWD = "123456" fun main () { login("wuleizhenshang" , "123456" , ::methodResponseResult) } fun methodResponseResult (msg: String , code: Int ) { println("最终登录结果为:$code ,$msg " ) } inline fun login (name: String , pwd: String , responseResult: (String , Int ) -> Unit ) { if (USER_NAME == name && USER_PWD == pwd) { responseResult("登录成功" , 200 ) } else { responseResult("登录失败" , 404 ) } }
函数类型作为返回类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 fun main() { val show1 = show("tt")//这里返回一个匿名函数 println(show1("wuleizhenshang", 20))//然后调用show1的返回的函数 } //这里再返回一个匿名函数,需要定义好入参和出参,不能直接使用类型推断完成 fun show(info: String): (String, Int) -> String { println("我是show函数,info:$info") //这里return一个函数类型,是一个匿名函数 //这里不能 return { name: String, age: Int -> "name:$name,age:$age" } }
匿名函数和具名函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 fun main () { showPersonInfo("wuleizhenshang" , 20 , '男' ) { } showPersonInfo("wuleizhenshang" , 20 , '男' , ::showResultImpl) } fun showResultImpl (result: String ) { println("显示结果:$result " ) } inline fun showPersonInfo (name: String , age: Int , sex: Char , showResult: (String ) -> Unit ) { val result = "name$name ,age:$age ,sex:$sex " showResult(result) }
第三阶段 可空性特点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 fun main () { */
安全调用操作符
1 2 3 4 5 6 7 8 9 fun main () { var name: String? = "zhangsan" name = null name?.capitalize() println(name) name = "hello" println(name) }
带let的安全调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 fun main () { var name: String? = null val r = name?.let { if (it.isBlank()){ "Default" }else { it } } println(r) }
非空断言操作符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 fun main () { var name: String? = "zhangsan" name = null name?.capitalize() println(name) val r = name!!.capitalize() println(r) }
使用if判断null情况
1 2 3 4 5 6 7 8 9 10 fun main () { var name: String? = null if (name!=null ){ val r = name.capitalize() println(r) }else { println("name为null" ) } }
空合并操作符
1 2 3 4 5 6 7 8 9 10 11 fun main () { var info: String? = "wuleizhenshang" info = null println(info ?: "原来你是null" ) println(info?.let { "{$it }" } ?: "原来你是null" ) }
异常处理与自定义异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 fun main () { try { var info: String? = null checkException(info) println(info!!.length) } catch (e: Exception) { println("有问题$e " ) } } fun checkException (info: String ?) { info ?: throw CustomException() } class CustomException : IllegalArgumentException ("你的代码不严谨" )
先决条件函数
1 2 3 4 5 6 7 8 9 10 11 12 fun main () { var value: String? = null var bool :Boolean = false require(bool) }
KT中的substring
1 2 3 4 5 6 fun main () { val index1 = INFO.indexOf('i' ) println(INFO.substring(0 , index1)) println(INFO.substring(0 until index1)) }
KT中的split
1 2 3 4 5 6 7 8 fun main () { val list = INFO.split(" " ) val (v1, v2, v3, v4) = list println("v1:$v1 ,v2:$v2 ,v3:$v3 ,v4:$v4 " ) }
KT中的replace
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 fun main () { val sourcePwd = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" println("原本密码是:$sourcePwd " ) val r1 = sourcePwd.replace(Regex("[AKMNO]" )) { when (it.value) { "A" -> "9" "K" -> "7" "M" -> "5" "N" -> "1" "O" -> "6" else -> it.value } } println("加密后的密码是:$r1 " ) }
==和===比较操作
1 2 3 4 5 6 7 8 9 fun main () { val a: Int = 999 val b: Int ? = a val c: Int ? = a println(b == c) println(b === c) }
字符串遍历操作
1 2 3 4 5 6 fun main () { val pwd = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" pwd.forEach { println("所有字符:$it " ) } }
数字类型的安全转换函数
1 2 3 4 5 6 7 8 9 10 11 12 fun main () { val number: Int = "666" .toInt() println(number) val number3: Int ? = "666.66" .toIntOrNull() println(number3) }
Double转Int
1 2 3 4 5 6 7 8 9 10 fun main () { println(65.4353 .toInt()) println(65.4353 .roundToInt()) println(65.8353 .roundToInt()) val r = "%.3f" .format(64.5732 ) println(r) }
apply内置函数
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 fun main () { val info = "name is Wuleizhenshang" println("info字符串的长度是:${info.length} " ) println("info最后一个字符是:${info[info.length - 1 ]} " ) println("info全部转换成小写:${info.toLowerCase()} " ) val infoNew: String = info.apply { println("info字符串的长度是:${length} " ) println("info最后一个字符是:${this[length - 1 ]} " ) println("info全部转换成小写:${toLowerCase()} " ) } println(infoNew) info.apply { println("info长度为:$length " ) }.apply { println("最后一个字符为${this[length - 1 ]} " ) }.apply { println("全部转成小写是${toLowerCase()} " ) } val file = File("D:\\a.txt" ) file.setExecutable(true ) file.setReadable(true ) println(file.readLines()) file.apply { setExecutable(true ) }.apply { setReadable(true ) }.apply { println(file.readLines()) } }