来自java的kotlin函数默认参数

标签 kotlin

鉴于以下 Kotlin 类:

class Foo {
   public fun bar(i: Int = 0): Int = 2 * i
}

我应该如何从 java/groovy 代码中调用没有任何参数的“bar”函数?

def f = new Foo()
f.bar() //throws:  java.lang.IllegalArgumentException: Parameter specified as non-null contains null

最佳答案

您现在可以在 Kotlin 中执行此操作。对于你的类方法,使用 @JvmOverloads annotation .

class Foo {
    @JvmOverloads public fun bar(name: String = "World"): String = "Hello $name!"
}

现在只需从 Java 中调用它:

Foo foo = new Foo();
System.out.println(foo.bar());
System.out.println(foo.bar("Frank"));

输出以下内容:

Hello World!

Hello Frank!

关于来自java的kotlin函数默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17348084/

相关文章:

android - 关系房间数据库 : The class must be either entity or database view

android - 导航库充气器为数据类抛出 ClassNotFoundException

android - 我可以在使用Kotlin的Android项目中集成和使用admob广告吗?

spring - 使用 maven spring 和 kotlin 创建多模块项目得到 Unresolved reference

javascript - 我/ Chrome : [INFO:CONSOLE(0)] "Not allowed to load local resource: file:///android_asset/downloader.png",

java - 什么时候应该创建 fragment View 模型?

android - 从我的 Android 应用调用 Google Pay Intent 时出现错误 "You have exceeded the maximum transaction amount set by your bank"

kotlin - 将列表转换为不同的列表和映射索引

spring-boot - spring-boot + kotlin + Junit中的单元测试POST API

kotlin - 最佳列表合并和操作技术