本文翻译自:What is the equivalent of Java static methods in Kotlin?

There is no static keyword in Kotlin. Kotlin中没有static关键字。

What is the best way to represent a static Java method in Kotlin? 用Kotlin表示static Java方法的最佳方法是什么?


#1楼

参考:https://stackoom.com/question/2jJZk/Kotlin中的Java静态方法等效于什么


#2楼

You place the function in the "companion object". 您将功能放置在“伴侣对象”中。

So the java code like this: 所以像这样的java代码:

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

will become 会变成

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

You can then use it from inside Kotlin code as 然后,您可以从Kotlin代码内部使用它,如下所示:

Foo.a();

But from within Java code, you would need to call it as 但是从Java代码中,您需要将其称为

Foo.Companion.a();

(Which also works from within Kotlin.) (这也来自Kotlin。)

If you don't like having to specify the Companion bit you can either add a @JvmStatic annotation or name your companion class. 如果您不想指定Companion位,则可以添加@JvmStatic批注或命名您的伴侣类。

From the 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. 但是,在JVM上,如果使用@JvmStatic批注,则可以将伴随对象的成员生成为实际的静态方法和字段。 See the Java interoperability section for more details. 有关更多详细信息,请参见Java互操作性部分。

Adding the @JvmStatic annotation looks like this 添加@JvmStatic注释如下所示

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

and then it will exist as a real Java static function, accessible from both Java and Kotlin as Foo.a() . 然后它将作为一个真正的Java静态函数存在,可以从Java和Kotlin中以Foo.a()

If it is just disliked for the Companion name, then you can also provide an explicit name for the companion object looks like this: 如果只是不喜欢Companion名称,那么您还可以为伴随对象提供一个明确的名称,如下所示:

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

which will let you call it from Kotlin in the same way, but from java like Foo.Blah.a() (which will also work in Kotlin). 它可以让您以相同的方式从Kotlin调用它,但可以从Foo.Blah.a()类的Java中调用它(在Kotlin中也可以使用)。


#3楼

A. Old Java Way : A.旧的Java方式:

  1. Declare a companion object to enclose a static method / variable 声明一个companion object以包含一个静态方法/变量

     class Foo{ companion object { fun foo() = println("Foo") val bar ="bar" } } 
  2. Use : 采用 :

     Foo.foo() // Outputs Foo println(Foo.bar) // Outputs bar 


B. New Kotlin way B.新科特林方式

  1. Declare directly on file without class on a .kt file. 直接声明文件, 而不声明.kt文件的

     fun foo() = println("Foo") val bar ="bar" 
  2. Use the methods/variables with their names . methods/variables与它们的名称一起使用 。 ( After importing them ) 导入后

    Use : 采用 :

     foo() // Outputs Foo println(bar) // Outputs bar 


#4楼

Docs recommends to solve most of the needs for static functions with package-level functions . Docs建议使用包级功能解决静态功能的大多数需求。 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. 可以使用package关键字在文件的开头指定文件的软件包。

Declaration 宣言

package foofun 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: 或者,如果您不使用import关键字:

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. 如果您只有Java经验,这似乎有些奇怪。 The reason is that kotlin is not a strictly object-oriented language. 原因是kotlin不是严格的面向对象语言。 You could say it supports methods outside of classes. 您可以说它支持类之外的方法。


#5楼

Write them directly to files. 将它们直接写入文件。

In Java (ugly): 在Java中(丑陋):

package xxx;
class XxxUtils {public static final Yyy xxx(Xxx xxx) { return xxx.xxx(); }
}

In Kotlin: 在科特林:

@file:JvmName("XxxUtils")
package xxx
fun xxx(xxx: Xxx): Yyy = xxx.xxx()

Those two pieces of codes are equaled after compilation (even the compiled file name, the file:JvmName is used to control the compiled file name, which should be put just before the package name declaration). 编译后,这两段代码相等(甚至是已编译的文件名, file:JvmName用于控制已编译的文件名,应将其放在包名声明之前)。


#6楼

You need to pass companion object for static method because kotlin don't have static keyword - Members of the companion object can be called by using simply the class name as the qualifier: 您需要为静态方法传递伴随对象,因为kotlin没有static关键字-可以通过仅使用类名作为限定符来调用伴随对象的成员:

package xxxclass ClassName {companion object {fun helloWord(str: String): String {return stringValue}}}

Kotlin中的Java静态方法等效于什么?相关推荐

  1. Kotlin程序用于打印JVM版本的Kotlin(打印Java属性)

    Here, we will create a Kotlin program to print Kotlin, JVM version (printing Java properties). As Ko ...

  2. kotlin调用类中的方法_一种轻松的方法来测试Kotlin中令人沮丧的静态方法调用

    kotlin调用类中的方法 by Oleksii Fedorov 通过Oleksii Fedorov 一种轻松的方法来测试Kotlin中令人沮丧的静态方法调用 (A stress-free way t ...

  3. Exception in thread main java.lang.Error: 无法解析的编译问题: 方法 main 不能声明为 static;只能在静态类型或顶级类型中才能声明静态方法

    Exception in thread "main" java.lang.Error: 无法解析的编译问题: 方法 main 不能声明为 static:只能在静态类型或顶级类型中才 ...

  4. java 静态方法重写_Java 类中可以覆盖静态方法吗?

    Java技术栈 www.javastack.cn 打开网站看更多优质文章 Java 类中可以覆盖静态方法吗? 不,你不能在Java中覆盖静态方法,但在子类中声明一个完全相同的方法不是编译时错误,这称为 ...

  5. 【开发环境】Android 命令行中执行 Java 程序 ( IntelliJ IDEA 中创建 Java / Kotlin 工程 | dx 打包 DEX 字节码文件 | dalvikvm 命令 )

    文章目录 前言 一.IntelliJ IDEA 中创建 Java / Kotlin 工程 二.准备 Java 和 Kotlin 代码 三.编译在 PC 上可执行的 Java / Kotlin JAR ...

  6. Java 类中可以覆盖静态方法吗?

    Java 类中可以覆盖静态方法吗? 不,你不能在Java中覆盖静态方法,但在子类中声明一个完全相同的方法不是编译时错误,这称为隐藏在Java中的方法. 你不能覆盖Java中的静态方法,因为方法覆盖基于 ...

  7. java中使用kotlin_在Kotlin中使用libGDX

    java中使用kotlin 最近,我一直在阅读有关不同语言的信息,以及它们可以为已经拥挤的软件开发人员带来什么,并且一种语言对我来说很突出:Kotlin. ( https://kotlinlang.o ...

  8. python kotlin_在Python,Java和Kotlin中标记参数和重载

    python kotlin 在多种语言之间跳来跳去可以帮助您注意到不同语言的习惯用法和最佳做法之间的某些差异. 比较有趣的差异之一与一个函数执行多项操作有关. Python 我们先来看一下Python ...

  9. 在Python,Java和Kotlin中标记参数和重载

    在多种语言之间跳来跳去可以帮助您注意到不同语言的习惯用法和最佳做法之间的某些差异. 比较有趣的差异之一与一个函数执行多项操作有关. Python 我们先来看一下Python. Python实际上无法重 ...

最新文章

  1. rancher添加私有仓库_CocoaPods搭建私有库
  2. Redis java使用
  3. 如果编程语言是超级英雄……
  4. fastjson与spring mvc整合的配置
  5. 手机html5性能测试工具,HTML5模块 性能方面8大测试环节_小米 M3_手机硬件频道-中关村在线...
  6. 北京计算机组织专家对,全球顶级专家齐聚北京 探讨计算机产业“大挑战”
  7. linux设置ntp开机同步时间同步,linux ntp时间同步
  8. NLP情感分析笔记(一):Baseline
  9. python logging 模块之TimedRotatingFileHandler 实现每天一个日志文件
  10. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_1-2.中大型公司里面项目开发流程讲解...
  11. SpringAOP之@EnableAspectJAutoProxy如何实现自动代理?
  12. JAVA基础语法——关键字
  13. iphone 6s 越狱
  14. 图片还原去遮挡_怎么去马赛克 还原图片去掉遮挡软件
  15. 散点图矩阵 pd.plotting.scatter_matrix
  16. 动态规划之流水作业调度问题
  17. Android校招复习资料整理
  18. 天蝎座最适合的职业-天蝎座不同型血适合工作分析
  19. angular 自定义打包文件名
  20. 从东京奥运会看js设计模式之发布订阅模式

热门文章

  1. SpringMVC、Spring和Struts的区别
  2. Android Stadio 所有的窗口都没有了
  3. 【剑指offer-Java版】05从尾到头打印链表
  4. (0030) iOS 开发之跳转之转场动画
  5. swift_003(Swift的?和!)
  6. Jmeter Md5加密操作之-------BeanShell PreProcessor
  7. out和ref之间的区别
  8. u-boot移植初步尝试-tiny4412
  9. js监控键盘大小写事件
  10. 字符编码笔记:ASCII,Unicode和UTF-8