函数中单元返回的目的是什么 [英] What is the purpose of Unit-returning in functions

查看:43
本文介绍了函数中单元返回的目的是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Kotlin 文档:

From the Kotlin documentation:

如果函数没有返回任何有用的值,则其返回类型为 Unit.Unit 是一种只有一个值的类型——Unit.VALUE.此值不必显式返回:

If a function does not return any useful value, its return type is Unit. Unit is a type with only one value — Unit.VALUE. This value does not have to be returned explicitly:

fun printHello(name : String?) : Unit { 
   if (name != null) 
     print("Hello, $name!") 
   else 
     print("Hi there!") 
   // We don't need to write 'return Unit.VALUE' or 'return', although we could 
}

函数中单元返回的目的是什么?为什么存在 VALUE?这是什么值?

What is the purpose of Unit-returning in functions? Why is VALUE there? What is this VALUE?

推荐答案

目的与 C 或 Java 的 void 相同.只有 Unit 是一个适当的类型,所以它可以作为泛型参数等传递.

The purpose is the same as C's or Java's void. Only Unit is a proper type, so it can be passed as a generic argument etc.

  1. 为什么我们不称它为Void":因为void"这个词的意思是没有",还有另一种类型,Nothing,意思是根本没有价值"",即计算没有正常完成(永远循环或抛出异常).我们无法承受意义的冲突.

  1. Why we don't call it "Void": because the word "void" means "nothing", and there's another type, Nothing, that means just "no value at all", i.e. the computation did not complete normally (looped forever or threw an exception). We could not afford the clash of meanings.

为什么 Unit 有值(即与 Nothing 不同):因为通用代码可以顺利运行.如果为泛型参数 T 传递 Unit,则为任何 T 编写的代码都将期望一个对象,并且必须有一个对象,即 Unit 的唯一值.

Why Unit has a value (i.e. is not the same as Nothing): because generic code can work smoothly then. If you pass Unit for a generic parameter T, the code written for any T will expect an object, and there must be an object, the sole value of Unit.

如何访问Unit的那个值:既然它是一个单例对象,就说Unit

How to access that value of Unit: since it's a singleton object, just say Unit

这篇关于函数中单元返回的目的是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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