请选择 进入手机版 | 继续访问电脑版
  • 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Kotlin中类似Java的static静态方法是什么?

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

问题描述

Kotlin中没有static关键字,也就是没有直接定义静态函数/静态方法的static关键字。那么用Kotlin表示类似JAVA的static静态方法的方式是?

 

最佳回答

将函数放在”companion object”中。

所以像这样的java代码:

class Foo {
  public static int a() { return 1; }
}

会变成

class Foo {
  companion object {
     fun a() : Int = 1
  }
}

然后,您可以从Kotlin代码内部使用它,如下所示:

Foo.a();

但是从Java代码中,您需要将其写作

Foo.Companion.a();

(注:上面这个写法在Kotlin中也有效。)

如果您不想指定Companion位,则可以添加@JvmStatic批注或命名您的Companion类。

根据docs:

Companion Objects

An object declaration inside a class can be marked with the companion keyword:

class MyClass {    companion object Factory {        fun create(): MyClass = MyClass()    } } 

Members of the companion object can be called by using simply the class name as the qualifier:

val instance = MyClass.create() 

However, on the JVM you can have members of companion objects generated as real static methods and fields, if you use the @JvmStatic annotation. See the Java interoperability section for more details.

添加@JvmStatic批注看起来像这样

class Foo {
  companion object {
    @JvmStatic
    fun a() : Int = 1;
  }
}

然后它将作为一个真正的Java静态函数存在,可以从Java和Kotlin中以Foo.a()的形式进行访问。

如果只是不喜欢Companion名称,则还可以为伴随对象提供一个明确的名称,如下所示:

class Foo {
  companion object Blah {
    fun a() : Int = 1;
  }
}

它可以让您以相同的方式从Kotlin调用它。在JAVA中可以用Foo.Blah.a()在Java中调用它(这个调用方法在Kotlin中也可以使用)。

 

 

第二种回答

A.旧的Java方式:

  1. 声明companion object以包含静态方法/变量
    class Foo{
    companion object {
        fun foo() = println("Foo")
        val bar ="bar"  
        }
    }
    
  2. 调用 :
    Foo.foo()        // Outputs Foo    
    println(Foo.bar) // Outputs bar
    

B.新的Kotlin(科特林)方式

  1. 直接在文件上声明,而无需在.kt文件上声明类。
    fun foo() = println("Foo")
    val bar ="bar"
    
  2. 使用methods/variables及其名称。 (导入后)采用 :
    foo()        // Outputs Foo          
    println(bar) // Outputs bar     
    

 

 

参考资料

  • What is the equivalent of Java static methods in Kotlin?

 


鲜花

握手

雷人

路过

鸡蛋
专题导读
上一篇:
python - Keras,如何获得每一层的输出?代码实例发布时间:2022-05-14
下一篇:
Pandas DataFrame遍历加速/性能优化发布时间:2022-05-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap