如何使用返回类型

如何使用返回类型

本文介绍了如何使用返回类型' void'声明Kotlin函数Java调用者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个完全用Kotlin编写的库,包括其公共API.现在,该库的用户使用Java,这里的问题是返回类型为Unit的Kotlin函数未编译为返回类型为void.结果是,对于有效无效的方法,Java端必须始终返回Unit.INSTANCE.可以以某种方式避免这种情况吗?

I have a library that is completely written in Kotlin including its public API. Now a user of the library uses Java, the problem here is that Kotlin functions with return type Unit are not compiled to return type void. The effect is that the Java side has always to return Unit.INSTANCE for methods that are effectivly void. Can this be avoided somehow?

示例:

Kotlin界面

interface Foo{
  fun bar()
}

Java实现

class FooImpl implements Foo{
   // should be public void bar()
   public Unit bar(){
      return Unit.INSTANCE
      // ^^ implementations should not be forced to return anything
   }
}

是否可以用不同的方式声明Kotlin函数,以便编译器生成voidVoid方法?

Is it possible to declare the Kotlin function differently so the compiler generates a void or Void method?

推荐答案

Voidvoid都可以,您只需要跳过Unit ...

Both Void and void work, you just need to skip that Unit...

Kotlin界面:

interface Demo {
  fun demoingVoid() : Void?
  fun demoingvoid()
}

实现该接口的Java类:

Java class implementing that interface:

class DemoClass implements Demo {

    @Override
    public Void demoingVoid() {
        return null; // but if I got you correctly you rather want to omit such return values... so lookup the next instead...
    }

    @Override
    public void demoingvoid() { // no Unit required...

    }
}

请注意,尽管 Kotlins参考指南从Java调用Kotlin" 并没有真正提及它, Unit文档可以:

Note that while Kotlins reference guide 'Calling Kotlin from Java' does not really mention it, the Unit documentation does:

我们知道,以下两个是等效的:

And as we know, the following two are equivalent:

fun demo() : Unit { }
fun demo() { }

这篇关于如何使用返回类型' void'声明Kotlin函数Java调用者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:51