Scala的.type和Java的.class文字 [英] Scala's .type and Java's .class literal

查看:144
本文介绍了Scala的.type和Java的.class文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个语言设计的角度思考为什么Scala已经删除了Java的类字面量(例如 String.class ),并替换为 classOf [String] ,但是添加了一个类型文字,其单例类似 Singleton.type ,而不是像 typeOf [Singleton ]

解决方案

这是我的理性化:



classOf [T]



classOf $ c> Predef 作为具有此签名的函数:

  def classOf [T] T] 

虽然由编译器实现,但使用函数语法是可能的根据语法创建任何特殊处理。



String.class 的替代方法意味着每个类都有具有字段的随播对象。因此,有两个问题:


  1. class 是一个关键字,问题,其中语法将需要一个特殊的情况下

  2. 如果你只创建类A companion对象,这将是奇怪的能够引用 A.class ,这将像访问字段在伴随 A

A.type: >

为什么 typeOf [A] 可能会造成混淆。它看起来像一个函数调用,但类型不生活在同一个世界作为函数结果(函数结果有类型,但类型本身只有在编译时才有意义)。我可以将一个类型归为一个变量:

  scala> val a:A.type = A 
a:A.type = A $ @ c21a68

我不能分配一个类型像一个函数返回:

  scala> val b = A.type 
< console>:1:error:identifier expected但找到'type'。
val b = A.type
^

是对象的成员:

  scala>对象A {type type1 = Int} 
定义模块A

scala> val x:A.type1 = 1
x:A.type1 = 1

不是一个大的延伸到 A.type 指的是对象类型 A 。注意, .type 不能用于引用单例对象的类型,所以它不是真的那么频繁。


I wonder from a language design perspective why Scala has removed Java's class literal (e. g. String.class) and replaced it with classOf[String], but has then added a "type literal" with its Singletons like Singleton.type instead of something like typeOf[Singleton]?

解决方案

Here is my rationalization:

classOf[T]

classOf is defined in Predef as a function with this signature:

def classOf[T]: Class[T]

Although it's implemented by the compiler, using the function syntax is possible without having to create any special treatment in terms of syntax. So that's one reason here to consider this option.

The alternative like String.class would imply that each class has a companion object with a field class. So there are two problems:

  1. class is a keyword, so that causes a problem where the syntax would require a special case for it
  2. if you just create class A without a companion object, it's would be odd to be able to refer to A.class, which would be like accessing the class field on the companion A.

A.type:

On why typeOf[A] may be confusing. It looks like a function call, but types don't live in the same world as function results (function results have types, but the type itself only makes sense at compile time). I can ascribe a type to a variable:

scala> val a: A.type = A
a: A.type = A$@c21a68

I can't assign a type like it's returned by a function:

scala> val b = A.type
<console>:1: error: identifier expected but 'type' found.
   val b = A.type
             ^

On the other hand types can be member of a object:

scala> object A { type type1 = Int }
defined module A

scala> val x: A.type1 = 1
x: A.type1 = 1

So it is not a big stretch to have A.type refer to the type of object A. Note that .type aren't used beyond referring to types of singleton objects, so it's not really that frequent.

这篇关于Scala的.type和Java的.class文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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