{}在返回函数类型中的目的是什么?

时间:2018-03-06 21:31:44

标签: scala

在以下函数声明中:

def f(x: Int): Int {} = x + 1

{}的目的是什么?

无论是否使用花括号,方法调用的结果都是相同的。

1 个答案:

答案 0 :(得分:8)

这只是一个空洞的改进。 在Scala中,任何类型都可以进行细化,从而约束原始类型的成员(例如,类型,val,defs)的定义。

例如:

trait Base { type T }

type BaseInt = Base { type T = Int }

这些成员不必在任何基类型中定义,精炼类型本身可以定义新成员。 并且对要改进的类型没有限制,允许改进AnyVal或其任何子类型。 所以下面的代码是完全合法的:

type A = Int { type C = Boolean; val a: String }

根据Scala specification

  

如果没有给出细化,则隐式添加空细化,   即T1 with … with TnT1 with … with Tn {}的简写。

因此,代码Int {}Int相同。

此外,根据规范,如果两种类型的细化完全匹配,则认为两种类型相同。因此,以下代码会导致编译时错误:

scala> type A = Int { type C = Boolean; val a: String }
defined type alias A

scala> val a: A = 10 
<console>:12: error: type mismatch;
 found   : Int(10)
 required: A
    (which expands to)  Int{type C = Boolean; val a: String}
       val a: A = 10
                  ^

但是由于这些改进在运行时由于擦除而不存在,如果你不使用改进中的成员,所有转换都是完全合法的:

scala> val a: A = 10.asInstanceOf[A] 
a: A = 10

此功能可用于实现tagged types,它们是相同的,并在运行时由某种原始类型表示,但可以在编译时进行区分。