在Scala中,为什么我可以在这里使用`Unit`作为返回类型? [英] In Scala, why can I use `Unit` as return type here?

查看:358
本文介绍了在Scala中,为什么我可以在这里使用`Unit`作为返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

  scala> def f(x:Int => Unit):单元= 1 
< console>:7:警告:纯表达式在语句位置中不做任何事情; (x:Int => Unit):单位= 1
^
f:(x:Int =>单位)单位
$你可能省略了必要的括号
def f b $ b scala> F(_ =&→2);
< console>:9:警告:纯表达式在语句位置中不做任何事情;您可能省略了必要的括号
f(_ => 2);
^

scala> F(_ =>列表(1,2));

上面的所有三个表达式在REPL中都有效(带有一些警告),但它们看起来有点混乱。

在第一个表达式中, f 的返回类型是 Unit ,它是 AnyVal 的子类型,但不是 Int 的超类型,因此,我无法理解为什么 1 可以用作返回值。



在第二个表达式中, _ => 2 也用 2 代替 Unit 作为返回值,与定义。



在第三个表达式中, _ =>列表(1,2)甚至使用 List , AnyRef 的子类型作为返回值,但REPL仍然不会抱怨这一点。



有人有关于为什么 Unit 可以容忍的想法这里的非子类型转换?谢谢!

解决方案

Scala会自动插入() code> Unit value)在这种情况下进行类型检查工作。所以你有什么相当于:

  def f(x:Int => Unit):Unit = {1; ()} 

这在Scala中被称为value discarding。从规范


值丢弃

如果 e 有一些值类型,并且期望的类型是 Unit e 通过嵌入来转换为预期的类型在术语
{e; ()}


像许多编程语言一样,这只是为了便于抛出表达式的返回值。这允许你创建一个只使用表达式的副作用的 Unit 类型的方法。


The codes are below:

scala> def f(x:Int => Unit):Unit = 1
<console>:7: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
       def f(x:Int => Unit):Unit = 1
                                   ^
f: (x: Int => Unit)Unit

scala> f(_=>2);
<console>:9: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
              f(_=>2);
                   ^

scala> f(_=>List(1,2));

All three expressions above worked in REPL(with some warnings), but they look a bit confusing..

In the first expression, f's return type is Unit, which is the subtype of AnyVal but not the Supertype of Int, therefore, I can't understand why 1 can be used as the returned value.

In the second expression, _=>2 also used 2 instead of Unit as the returned value, which conflicts with the definition.

In the third expression, _=> List(1,2) even uses List, subtype of AnyRef as the returned value, but the REPL still doesn't complain about this..

Does anyone have ideas about why Unit can tolerate the non-subtype type conversion here? Thanks!

解决方案

Scala will automatically insert () (the singleton Unit value) in this case to make the typechecking work. So what you have is equivalent to:

def f(x:Int => Unit):Unit = { 1; () }

This is known as "value discarding" in Scala. From the spec:

Value Discarding

If e has some value type and the expected type is Unit, e is converted to the expected type by embedding it in the term { e; () }

Like in many programming languages, this is meant to facilitate just "throwing out" the return value of the expression. This allows you to make a method of type Unit that only uses the side effects of an expression.

这篇关于在Scala中,为什么我可以在这里使用`Unit`作为返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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