安卓系列之 kotlin 基础知识(二)

161 阅读1分钟

函数

  1. fun
    函数声明关键字
  2. 格式
    可见性修饰符 fun 函数名(参数:参数类型):返回类型
    {
    执行代码块
    }
public fun sum(a: Int, b: Int): String {
    return "sum:${a+b}"
}
  1. 默认值参(缺省值)
    函数方法本身具有参数默认值
/**
 * age有默认值,调用方法的时候可以不传
 */
fun getStudentInfo(id: Int, name: String, age: Int = 18) {
    println("id : $id , 姓名 : $name , 年龄 : $age")
}
getStudentInfo(1"马冬梅")
getStudentInfo(1"马冬梅"12)
  1. 命名值参
    调用方法传参数的时候指定参数的名字(命名值参),就可以不按顺序传入参数
fun getStudentInfo(id: Int, name: String, age: Int = 18){
    println("id : $id , 姓名 : $name , 年龄 : $age")
}
getStudentInfo(name = "马冬梅", id = 2, age = 22)
  1. Unit 函数
    Unit 相当于 Java 的 void,表示函数没有返回值
  2. Nothing 类型
    TODO("reason"),抛出异常,不执行后续代码
  3. 反引号函数命名法则
    可以使用空格和特殊字符加上反引号,即可对函数方法特殊命名,常用于测试

匿名函数(lambda)

  1. 格式
    val 变量名:(变量类型)->返回类型={变量名->
    代码块
    }
  2. 作为参数
    匿名函数可以作为参数传递给其他函数,例如具名函数的参数可以是一个匿名函数
/**
 * 匿名函数
 */
private val thisStudentInfo = { id: Int, name: String ->
        "id : $id , 姓名 : $name"
}

/**
  * 具名函数带有匿名函数参数
  */
private fun asAParameter(name: String, studentInfo: (IntString) -> String) {
   println("this content created by " + studentInfo(18, name))
}

asAParameter("马冬梅", thisStudentInfo)
  1. 作为返回值
    匿名函数可以作为其他函数的返回值
/**
  * 匿名函数作为返回
  */
private fun asReturn(): (String) -> String {
   val id = Math.random() * 10
   return { myName: String ->
       "$myName 's id is $id"
   }
}

fun test() {
    val asReturn = asReturn()
    print(asReturn("马冬梅"))
}
  1. 返回结果
    最后一行的语句即返回结果,不需要 return 关键字
  2. it 关键字
    若匿名函数的参数有且只有一个,可以用 it 关键字来表示参数名
val myTest: (a: Int) -> Unit = {
    print("$it"//这里的it指a
}

函数引用

  1. 通常使用::表示引用函数
  2. 可以把一个具名函数转换成一个值参
  3. 使用匿名函数的地方都可以使用函数引用

图片

函数引用

Java 的匿名内部类和 kotlin 的简写匿名函数

前提:必须要基于接口或抽象类的应用
Java 的匿名内部类

//Java的匿名内部类和kotlin的简写匿名函数
public interface WhoCallBack {
    void draw();
}

public static void showWhoIsDrawer(WhoCallBack whoCallBack) {
    whoCallBack.draw();
}

public void test() {
    showWhoIsDrawer(new WhoCallBack() {
        @Override
        public void draw() {
            System.out.print("画家是谁谁谁");
        }
    });
}

前提:kotlin 中函数的最后一个参数是匿名函数
kotlin 的简写匿名函数

//Java的匿名内部类和kotlin的简写匿名函数
fun showDrawer(content: String, who: (nameString) -> String) {
    print("this $content is draw by $who")
}

fun test() {
    showDrawer("草莓画") {
        "作家 $it"
    }
}

kotlin 标准库函数

let

方法返回值:
lambda 最后一行代码
常用场景:
1.对象需要空判断
2.明确变量的作用域范围

/**
 * let,返回最后一行代码
 */
fun testLet() {
    //判断是否为空,若空则不执行
    val a: String? = null
    a?.let {
        print(a.length)
    }

    val b = "test"
    val bLength = b.let {
        it.length + 2
    }
}

also

方法返回值:
传入对象的本身
常用场景:
在 let 的基础上,同时需要返回对象本身 优点:
因为返回值是对象,所以可链式调用

/**
 * also
 * 返回对象
 */
fun testAlso() {
    val c = 2
    c.also {
        it * 2 //返回c对象,即c=4
    }
}

run

方法返回值:
lambda 最后一行代码
常用的场景:
1.用某个对象的多个属性值时统一做空判断
2.明确作用域范围
3.方法内可省略对象名

/**
 * run
 * 返回最后一行代码
 */

fun testRun() {
    class Student {
        val name: String? = null
        val age: Int? = null

        constructor(name: String, age: Int)
    }

    val student = Student(""1)
    student?.run {
        print("这名学生的姓名是 $name,年龄是 $age"//统一做空判断
    }
}

apply

方法返回值:
传入对象的本身
常用的场景:
一个对象需要设置它的一些属性并且需要返回对象本身,例如设置文件的可读性,然后开始读取文件内容
优点:
因为返回值是对象,所以可链式调用

/**
 * 例如:利用apply给列表默认首个数据
 */
fun testApply() {
    val aList = arrayListOf<String>()
    aList.apply {
        add("我是列表的头儿")//省略了aList.因为是匿名函数
    }
    Log.e("aList的size", aList.size.toString())//打印结果:aList的size: 1
}

with

常用场景:
对一个对象做多种操作

/**
 * with
 */
fun testWith() {
    class Teacher {
        val name: String? = null
        val age: Int? = null

        constructor(name: String, age: Int)

    }

    val teacher = Teacher("陈老师"22)
    with(teacher) {
        print("$name")
        print("$age")
    }
}

taskIf&&taskUnless

作用类似于过滤器
返回值:
返回对象或者 null
优点:
避免重复建立变量

/**
 * takeIf
 * takeUnless
 */
fun testTask() {
    val random = Random.nextInt(100)
    val a = random.takeIf { it % 2 == 0 } //偶数则返回自己,否则返回null
    val b = random.takeUnless { it % 2 == 0 } //偶数则返回null,否则返回自己
    Log.e("===","a:$a,b:$b")
}

repeat

重复执行,传入执行次数

/**
 * repeat
 */
fun testRepeat() {
    var i = 0
    repeat(3) {
        i++
        Log.e("执行""" + i)
    }
}

项目 github 地址

github.com/ElaineTaylo…

若帅哥美女对该系列文章感兴趣,可微信搜索公众号(木子闲集)关注更多更新文章哦,谢谢~