空返回类型在Kotlin中是什么意思 [英] What does Void return type mean in Kotlin

查看:223
本文介绍了空返回类型在Kotlin中是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Kotlin中创建函数而不返回值.我写了一个类似Java的函数,但是使用Kotlin语法

I tried to create function without returning value in Kotlin. And I wrote a function like in Java but with Kotlin syntax

fun hello(name: String): Void {
    println("Hello $name");
}

我有一个错误

错误:函数中需要使用'return'表达式 块体('{...}')

Error:A 'return' expression required in a function with a block body ('{...}')

经过几次更改后,我得到了具有可空Void作为返回类型的工作函数.但这不是我真正需要的

After couple of changes I've got working function with nullable Void as return type. But it is not exactly what I need

fun hello(name: String): Void? {
    println("Hello $name");
    return null
}

根据 Kotlin文档单元类型对应Java中的void类型.因此,在Kotlin中没有返回值的正确函数是

According to Kotlin documentation Unit type corresponds to the void type in Java. So the correct function without returning value in Kotlin is

fun hello(name: String): Unit {
    println("Hello $name");
}

fun hello(name: String) {
    println("Hello $name");
}

问题是:Void在Kotlin中是什么意思,如何使用,这种用法的优点是什么?

The question is: What does Void mean in Kotlin, how to use it and what is the advantage of such usage?

推荐答案

Void是普通的Java类,在Kotlin中没有特殊含义.

Void is a plain Java class and has no special meaning in Kotlin.

与您在Kotlin中使用Integer的方式相同,它是Java类(但应使用Kotlin的Int).您正确地提到了不返回任何内容的两种方法.因此,在Kotlin中,Void是某物"!

The same way you can use Integer in Kotlin, which is a Java class (but should use Kotlin's Int). You correctly mentioned both ways to not return anything. So, in Kotlin Void is "something"!

您收到的错误消息准确地告诉了您.您将(Java)类指定为返回类型,但未在代码块中使用return语句.

The error message you get, tells you exactly that. You specified a (Java) class as return type but you didn't use the return statement in the block.

如果您不想返回任何东西,请坚持这样做:

Stick to this, if you don't want to return anything:

fun hello(name: String) {
    println("Hello $name")
}

这篇关于空返回类型在Kotlin中是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆