Scala 中 Null/Nothing/Unit 的用法 [英] Usages of Null / Nothing / Unit in Scala

查看:23
本文介绍了Scala 中 Null/Nothing/Unit 的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了:http://oldfashionedsoftware.com/2008/08/20/a-post-about-nothing/

据我所知,Null 是一个 trait,它唯一的实例是 null.

As far as I understand, Null is a trait and its only instance is null.

当一个方法接受一个 Null 参数时,那么我们只能直接向它传递一个 Null 引用或 null,而不能传递任何其他引用,即使它是 null (nullString: String = null 例如).

When a method takes a Null argument, then we can only pass it a Null reference or null directly, but not any other reference, even if it is null (nullString: String = null for example).

我只是想知道在哪些情况下使用这个 Null 特性会很有用.还有我没有看到更多例子的Nothing特征.

I just wonder in which cases using this Null trait could be useful. There is also the Nothing trait for which I don't really see any more examples.

我也不太明白使用 Nothing 和 Unit 作为返回类型有什么区别,因为两者都不返回任何结果,例如,当我有一个执行日志记录的方法时,如何知道使用哪个?

I don't really understand either what is the difference between using Nothing and Unit as a return type, since both doesn't return any result, how to know which one to use when I have a method that performs logging for example?

您是否将 Unit/Null/Nothing 用作返回类型以外的其他东西?

Do you have usages of Unit / Null / Nothing as something else than a return type?

推荐答案

只有在方法永不返回时才使用 Nothing(意味着它不能通过返回正常完成,它可能会抛出异常).没有什么是永远不会实例化的,并且是为了类型系统的利益而存在的(引用 James Iry:"Scala 具有底部类型的原因与其在类型参数中表达差异的能力有关.").来自您链接到的文章:

You only use Nothing if the method never returns (meaning it cannot complete normally by returning, it could throw an exception). Nothing is never instantiated and is there for the benefit of the type system (to quote James Iry: "The reason Scala has a bottom type is tied to its ability to express variance in type parameters."). From the article you linked to:

Nothing 的另一种用途是作为永远不会的方法的返回类型返回.如果你考虑一下,这是有道理的.如果一个方法的返回类型是Nothing,并且绝对不存在Nothing的实例,那么这样的方法绝不能返回.

One other use of Nothing is as a return type for methods that never return. It makes sense if you think about it. If a method’s return type is Nothing, and there exists absolutely no instance of Nothing, then such a method must never return.

您的日志记录方法将返回 Unit.有一个值 Unit,所以它实际上可以返回.来自 API 文档:

Your logging method would return Unit. There is a value Unit so it can actually be returned. From the API docs:

Unit 是 scala.AnyVal 的一个子类型.类型只有一个值单位,(),并且不由底层中的任何对象表示运行时系统.返回类型为 Unit 的方法类似于 Java声明为 void 的方法.

Unit is a subtype of scala.AnyVal. There is only one value of type Unit, (), and it is not represented by any object in the underlying runtime system. A method with return type Unit is analogous to a Java method which is declared void.

这篇关于Scala 中 Null/Nothing/Unit 的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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