Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kotlin Extensions #73

Open
alwaystest opened this issue May 7, 2018 · 0 comments
Open

Kotlin Extensions #73

alwaystest opened this issue May 7, 2018 · 0 comments

Comments

@alwaystest
Copy link
Owner

Kotlin Extensions

标签(空格分隔): Kotlin


Kotlin有一个大量使用的语法糖,叫Extensions

Google甚至在Github搞了一个开源的Lib https://github.com/android/android-ktx

这个功能实现的效果很神奇,看起来像是可以给一个类增加一个这个类没有实现的方法。

比如

fun Solution.test () {
    println("test")
}

class Solution {

}

fun main(args: Array<String>) {
    val solution = Solution()
    solution.test()
}

实现的原理很简单。
在Java里调用一次Kotlin的函数就明白啦

import kotlin.Solution;
import kotlin.SolutionKt;

public class Main {

    public static void main(String[] args) {
        Solution solution = new Solution();
        SolutionKt.test(solution);
    }
}

就是一个静态方法调用嘛,Kotlin在编译的时候把扩展函数解语法糖,变成SolutionKt.class 里的一个静态方法,并且把Caller当作该方法的第一个参数传进去。

文档里,这个特性的Motivation就是想把之前的*Utils.xxx()给简化掉。

乍一看android-ktx,特别困惑的一点是 这个Lib里面这么多扩展方法,Kotlin怎么知道去哪里找方法对应的实现呢?

package kotlin.inner

fun Solution.test () {
    println("test")
}
package kotlin

import kotlin.inner.test

class Solution {

}

fun main(args: Array<String>) {
    val solution = Solution()
    solution.test()
}

在Kotlin里面调用并不需要找XyzKt这种类了,直接导入package就好,剩下的全部交给编译器啦。

Ref

  1. https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#package-level-functions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant