单位归还功能的目的是什么 [英] What is the purpose of Unit-returning in functions

查看:97
本文介绍了单位归还功能的目的是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Kotlin文档中:

From the Kotlin documentation:

如果函数不返回任何有用的值,则其返回类型为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"表示无",还有另一种类型,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天全站免登陆