What is the equivalent of Java static methods in Kotlin?

前端 未结 28 1198
眼角桃花
眼角桃花 2020-11-27 09:03

There is no static keyword in Kotlin.

What is the best way to represent a static Java method in Kotlin?

28条回答
  •  半阙折子戏
    2020-11-27 09:59

    Docs recommends to solve most of the needs for static functions with package-level functions. They are simply declared outside a class in a source code file. The package of a file can be specified at the beginning of a file with the package keyword.

    Declaration

    package foo
    
    fun bar() = {}
    

    Usage

    import foo.bar
    

    Alternatively

    import foo.*
    

    You can now call the function with:

    bar()
    

    or if you do not use the import keyword:

    foo.bar()
    

    If you do not specify the package the function will be accessible from the root.

    If you only have experience with java, this might seem a little strange. The reason is that kotlin is not a strictly object-oriented language. You could say it supports methods outside of classes.

    Edit: They have edited the documentation to no longer include the sentence about recommending package level functions. This is the original that was referred to above.

提交回复
热议问题