美文网首页
Kotlin中的函数式接口

Kotlin中的函数式接口

作者: 盛世光阴 | 来源:发表于2021-06-11 12:13 被阅读0次

    前言

    Kotlin 是一种在 Java 虚拟机上运行的静态类型编程语言,被称之为 Android 世界的Swift,在Google I/O 2017中,Google 宣布 Kotlin 成为 Android 官方开发语言

    函数式接口

    有且仅有一个抽象方法的接口(Single abstract method),被称作函数式接

    Java中的函数式接口

    可以被FunctionInterface进行注解,标识这个接口是一个函数式接口,可以直接使用lambda的方式引用,并且如果接口内部接口变化,如果不符合函数式接口还会报错提示

    @FunctionalInterface
    public interface Function<T, R> {
        R apply(T t);
    }
    
    Function<String,Person> func = name > {return new Person(name);};
    
    //等价于
    Function<String,Person> func = Person::new;
    

    Kotlin中的函数式接口

    从kotlin 1.4开始,Kotlin引入了函数式接口,和Java的定义相同,只不过表示方式不同

    fun interface AccountCallBack {
        fun account(name:String): Account
    }
    
    val callBack = object : AccountCallBack {
        override fun account(name:String): Account {
             return Account()
        }
    }
    val callBack = AccountCallBack { Account() }
    

    欢迎关注Mike的简书

    Android 知识整理

    相关文章

      网友评论

          本文标题:Kotlin中的函数式接口

          本文链接:https://www.haomeiwen.com/subject/aoepeltx.html