什么时候没有合法收货人? [英] When is Nothing a legal receiver?

查看:74
本文介绍了什么时候没有合法收货人?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为其他所有类型的子类型,假设的Nothing类型值将传递给任何函数.但是,尽管这样的值可以用作toString()的接收器,但不能作为unary_!(以及其他).

Being the subtype of every other type allows a hypothetical Nothing typed value to be passed to any function. However, although such a value can serve as receiver for toString() it can't for unary_! (among others).

object Foo {
    def dead(q: Nothing): Unit = {
        println(q);
        q.toString();
        ((b: Boolean) => !b)(q);
        !q; // value unary_! is not a member of Nothing
    }
}

这是错误还是功能?

注意:

  1. 这是我在Kotlin上问的等效问题的Scala版本.
  2. 向上投射的作品:!(q.asInstanceOf[Boolean])

推荐答案

您不需要上流.您只需要归因某种具有方法unary_!的类型:

You don't need upcasting. You only have to ascribe some type which has a method unary_!:

def dead(q: Nothing): Unit = {
  !(q: Boolean)
}

如果没有显式类型说明,则无法解析方法unary_!,因为即使NothingBoolean子类型,它也不是子类 Boolean,因此编译器无法在Nothing的继承层次结构中找到方法unary_!.

Without an explicit type ascription, the method unary_! simply cannot be resolved, because even though Nothing is a subtype of Boolean, it's not a subclass of Boolean, therefore the compiler can not find a method unary_! in the inheritance hierarchy of Nothing.

您可以定义此类方法和函数的事实也不是错误.以下是一个完全有效的程序,该程序使用输入类型为Nothing的函数来产生完全有意义的结果0,而不会引发任何错误或类似的结果:

The fact that you can define such methods and functions is not a bug either. The following is a completely valid program that uses a function with input type Nothing to produce a perfectly meaningful result 0, without throwing any errors or anything like it:

def foo[X](xs: List[X], f: (Int, X) => Int) = {
  xs.foldLeft(0)(f)
}

foo(Nil, (i: Int, n: Nothing) => 42)

在类型系统中出现Nothing是一个非常好的主意,因为它是一个初始对象(对于每个其他类型A,只有一个函数Nothing => A),并且简化了很多事情,因为它不会强迫您处理各种奇怪的极端情况.

The presence of Nothing in the type system is a Really Good Idea, because it's an initial object (for each other type A, there is exactly one function Nothing => A), and it simplifies lot of things, because it does not force you to deal with all kind of strange corner cases.

这篇关于什么时候没有合法收货人?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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