Kotlin中的内置函数基本使用

645 阅读4分钟

Kotlin中的内置函数:apply

  • 概述:

    • 返回值:返回调用者本身

      • 可以实现链式调用()

        image-20211202181323328

    • 函数体(匿名函数):内部持有this指针指向调用者

  • 代码实现:

     package ttest
     ​
     fun main(){
         val msg = "Hello World"
         println("普通调用")
         println("打印字符串:$msg")
         println("字符串的长度:$msg.length")
         println("最后一个字符是:${msg[msg.length-1]}")
         println("全小写输出:${msg.toLowerCase()}")
         println("使用apply函数")
         val msg1 = msg.apply {
             println("验证内置this,输出原字符串:$this")
             println("字符串长度:${length}")
         }
         println("打印msg.apply的返回值" + msg1)
         println("测试链式调用")
         msg.apply {
             print("打印原始字符串:$this")
         }.apply {
             println("字符串长度为:$length")
         }.apply {
             println("全小写输出:${toLowerCase()}")
         }
     }
    
  • 运行截图:

    image-20211202181037050

kotlin中let内置函数

  • kotlin中集合的基本操作:

    • 代码

       /*集合基本操作
       *   1.采用listOf 定义一个集合
       *   2.list.first:取出集合的第一个元素
       * */
       val list = listOf(6, 5, 2, 3, 5, 7)
       val value1 = list.first() // 第一个元素
       val result1 = value1
       println("使用集合内置属性first,取出集合第一个元素 $result1")
      
    • 运行截图:

      image-20220304144605926

  • let函数与apply做对比:配合匿名函数

    • 返回值不同:

      • let的返回值:匿名函数的最后一行
      • apply的返回值:为其调用者
    • 内部持有不同:但均指向其调用者

      • let内部持有it
      • apply内部持有this
    • 代码:

           /*let配合匿名函数与apply作对比
           *   1.let内部持有it:集合.let,it就是调用let的集合
           *   2.apply内部持有this:字段.apply,this就是调用apply的调用者
           *   3.let函数+匿名函数的返回值,是匿名函数的最后一行;内部自动类型推断
           *   4.apply+匿名函数的返回值:为apply的调用者本身,不是匿名函数的最后一行
           * */
           val result2 = listOf(6, 5, 2, 3, 5, 7).let {
               // it == list集合
               println("使用let函数借助其内部持有的it,取出集合第一个元素"+it.first())
               println("验证let函数内部持有的是it $it")
       //        println(this),这个要报错
               true
           }
           println("验证let函数的返回值为,匿名函数的最后一行  $result2" )
       ​
       ​
           val info  = "hello world"
           val infoBack = info.apply {
               true
               println("验证apply函数内部持有的是this $this")
       //        println(it),这个要报错
           }
           println("验证apply的返回值,为其调用者(字符串hello world)  $infoBack")
      
    • 运行截图:

      image-20220304145002819

  • 对空值处理:一般处理办法:普通函数+if表达式(在kotlin中if是带有返回值的)

    • 函数定义代码
     // 空值函数检查
     fun getMethod1(value: String?) : String {
         return if (value == null) "传入的参数value为空值,请检查" else "传入的参数value不为空值,且value为:${value}"
     }
     ​
     // 空值函数检查,简化版本
     fun getMethod2(value: String?) = if (value == null) "传入的参数value为空值,请检查" else "传入的参数value不为空值,且value为:${value}"
    
    • 在主函数中调用

           println(getMethod1(null))
           println(getMethod2("WAsbry"))
      
    • 运行截图:

      image-20220304145630056

  • 对空值处理:let函数+空合并操作符

    • 函数定义代码

       fun getMethod3(value: String?) : String {
           return value?.let {
               "传入的参数value不为空值,且value为:$it"
           } ?: "传入的参数value为空值,请检查"
       }
       ​
       // let方式 + 空合并操作符 对值判null,并返回 简化版本
       fun getMethod4(value: String?) =
            value?.let {
               "传入的参数value不为空值,且value为:$it"
           } ?: "传入的参数value为空值,请检查"
      
    • 在主函数中进行调用

           println(getMethod3(null))
           println(getMethod4("WAsbry"))
      
    • 运行截图:

      image-20220304145958919

Kotlin中的内置函数:run

  • 概述:

    • run函数内部持有this指针,指向其调用者(与apply类似)

    • run配合匿名函数,其返回值为匿名函数最后一行

    • run配合具名函数,默认将其内部持有的this作为具名函数参数,并可实现链式调用

    • 链式调用细节:

      • 每一条链的返回值,由该链的具名函数所决定
      • 上链的返回值作为下链的参数使用
      • 整个链式调用的返回值为其最后一条链的返回值
  • 验证run函数内部持有this指针与run配合匿名函数,其返回值为匿名函数最后一行

    • 代码:

           val str = "Hello World"
           val runBack = str.run {
               println("打印run内部持有的this: $this")
               true
           }
           println("run 配合匿名函数,验证其返回值为匿名函数的最后一行 $runBack")
      
    • 运行截图:

      image-20220304152906539

  • run配合链式调用细节:

    • 代码:

       //在主函数中使用run配合具名函数实现链式调用
       val str = "Hello World"
       str
               .run(::isLong) // this == str本身
               .run(::showText) // this == isLong返回的boolean值
               .run(::mapText)
               .run(::println)//调用系统具名函数
       ​
       //具名函数定义
       fun isLong(str: String) /* : Boolean */ = if (str.length > 5) true else false
       ​
       fun showText(isLong: Boolean) /*: String */ = if (isLong) "你的字符串合格" else "你的字符串不合格"
       ​
       fun mapText(getShow: String) /*: String */ = "$getShow"
       ​
      
    • 运行截图:

      image-20220304153856483

  • run 使用匿名函数实现链式调用

    • 代码:

       //在主函数中,run+匿名函数实现链式调用
           val str = "Hello World"
           str
               .run {
                   if (length > 5) true else false
               }
               .run {
                   if (this) "你的字符串合格" else "你的字符串不合格"
               }
               .run {
                   "$this"
               }
               .run {
                   println(this)
               }
      
    • 运行截图:

      image-20220304160534774

    细节:这个let函数也可以实现链式调用,将上一条链的返回值作为下一条链的参数,注意内部持有就行了

     //主函数处理:
     str.let(::isLong) // it == str本身
         .let(::showText) // it == isLong返回的boolean值
         .let(::mapText) // it == str本身
         .let(::println) // it == str本身
     ​
         println()
     //定义具名函数
     ​
     fun isLong(str: String) /* : Boolean */ = if (str.length > 5) true else false
     ​
     fun showText(isLong: Boolean) /*: String */ = if (isLong) "你的字符串合格" else "你的字符串不合格"
     ​
     fun mapText(getShow: String) /*: String */ = "$getShow"
    

Kotlin中的内置函数:with

  • 概述:

    • 基本与run类似(内部持有this,指向调用者;配合匿名函数,其返回值为匿名函数最后一行),但是使用上有一定区别:需要将调用者作为函数参数进行传入
  • 代码:with配合具名函数实现链式调用

     //主函数:with配合具名函数实现链式调用
     val str = "Hello World"
     ​
         // 具名操作
         /*with(str) {
             this == str本身
         }*/
         val r1 = with(str, ::getStrLen)
         val r2 = with(r1, ::getLenInfo)
         val r3 = with(r2, ::getInfoMap)
         with(r3, ::show)
     //具名函数定义:
     fun getStrLen(str: String) = str.length
     fun getLenInfo(len: Int) = "你的字符串长度是:$len"
     fun getInfoMap(info: String) = "$info"
     fun show(content: String) = println(content)
    
  • 运行截图:with配合具名函数实现链式调用

    image-20220304171803367

  • 代码:with配合匿名函数实现链式调用

     with(with(with(with(str) {
             length
         }) {
             "你的字符串长度是:$this"
         }){
             "【$this】"
         }){
             println(this)
         }
    
  • 运行截图:with配合匿名函数实现链式调用

    image-20220304171829955

Kotlin内置函数:takeIf

  • 概述:

    • 配合匿名函数,当匿名函数返回值为true时,takeIf返回调用者;为false,takeIf返回null
    • 内部持有it,指向调用者本身
  • 代码:模拟用户校验(简陋版本)

     fun main() {
             val result = checkPermissionAction("wasbry", "123456")
             if (result != null) {
                 println("登录成功,当前用户为:${result}")
             } else {
                 println("登录失败")
             }
     }
     // 用户校验
     public fun checkPermissionAction(name: String, pwd: String) : String? {
         return name.takeIf { permissionSystem(name, pwd) }
     }
     ​
     // 后台的用户管理系统
     private fun permissionSystem(username: String, userpwd: String) : Boolean {
         return if (username == "Root" && userpwd == "123456") true  else false
     }
    
  • 运行截图:模拟用户检验

    image-20220304175615538

  • 代码:模拟用户校验(takeIf+空操作合并符)

     fun main(){
         // 真正的用途
         println(checkPermissionAction2("wasbry", "123456"))
     }
     ​
     // takeIf + 空合并操作符
     public fun checkPermissionAction2(name: String, pwd: String) : String {
         return name.takeIf { permissionSystem(name, pwd) } ?: "登录失败"
     }
     ​
     // 权限系统
     private fun permissionSystem(username: String, userpwd: String) : Boolean {
         return if (username == "Root" && userpwd == "123456") true  else false
     }
    
  • 运行截图:模拟用户校验(takeIf+空操作合并符)

    image-20220304180024470

Kotlin内置函数:takeUnless

  • 概述:

    • 配合匿名函数,当匿名函数返回值为true时,takeUnless返回null;为false,takeUnless返回调用者
    • 内部持有it,指向调用者本身
  • 应用场景:takeUnless+it.isNullOrBlank() 一起使用,可以验证字符串有没有初始化等功能

  • 代码:

     class Manager {
     ​
         private var infoValue: String? = null
     ​
         fun getInfoValue() /* : String? */ = infoValue
     ​
         fun setInfoValue(infoValue: String) {
             this.infoValue = infoValue
         }
     }
     ​
     fun main() {
         val manager = Manager()
         
         // manager.setInfoValue("AAA")
     ​
         // 小结:takeUnless+it.isNullOrBlank() 一起使用,可以验证字符串有没有初始化等功能
         val r  = manager.getInfoValue().takeUnless { it.isNullOrBlank() } ?: "未经过任何初始化值"
         println(r)
     }
    
  • 运行截图:

    image-20220304180718052