您的位置:首页 > 游戏 > 游戏 > android kotlin复习 Anonymous function 匿名函数

android kotlin复习 Anonymous function 匿名函数

2025/2/14 6:20:42 来源:https://blog.csdn.net/jwbabc/article/details/141960034  浏览:    关键词:android kotlin复习 Anonymous function 匿名函数

1、还是先上个图,新建kt:

2、代码:

package com.jstonesoft.myapplication.testfun main(){val count = "helloworld".count()println(count);println("------------------------")var count2 = "helloworld".count(){it == 'l';}
//    count2 = "helloworld".count{
//        it == 'l';
//    }println(count2);println("------------------------")// lambda 隐式返回,不需要return,最后一行为返回值,而且类型要一致。//1.定义val countMethod: () -> String;//2.实现countMethod = {val i = 999;"$i abc";}//3.调用println(countMethod());// lambda 1.函数声明+实现val countMethod2 : (String, Int) -> String = { username, old ->val result = "姓名:$username, 年龄:$old"println(result);result;}//2.函数调用countMethod2("flower and flower fish",18);//2.等价调用countMethod2.invoke("flower and flower fish",18);println("------------------------")//一个参数是会有一个it参数val countMethod3 : (String) -> String = {"$it flower and flower fish"}val result = countMethod3("hi");println(result)//一个参数是会有一个it参数val countMethod4 : (Double) -> String = {"$it flower and flower fish"}val result2 = countMethod4(12.32);println(result2)println("------------------------")//匿名函数,自动推断,返回值类型。val countMethod5 = { username:String , old:Int ->val result = "您好,$username, 您的年龄:$old";println(result)result}countMethod5("flower and flower fish",18);//匿名函数,自动推断,返回值String类型。val countMethod6 = {val result = "hi"result;}println(countMethod6());}

3、输出:

4、说明:

  • 计算字符串的长度,直接用str.count();
  • 计算字符串中某个字符出现的次数,直接用str.count(){ it == 'l'; //要查询的字符 }
  • lambda 隐式返回,不需要return,最后一行为返回值,而且类型要一致。
  • lambda 1.函数声明+实现 ==》(参数)-> (返回值){ 函数体 ,最后一行为返回值 。}
  • 一个参数是会有一个it参数
  • 匿名函数,自动推断,返回值类型。

这个匿名函数与Swift中的闭包是一样的。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com