Scala的.type和Java的.class文字 [英] Scala's .type and Java's .class literal
问题描述
String.class
),并替换为 classOf [String]
,但是添加了一个类型文字,其单例类似 Singleton.type
,而不是像 typeOf [Singleton ] 解决方案这是我的理性化:
classOf [T]
classOf
$ c> Predef
作为具有此签名的函数: def classOf [T] T]
虽然由编译器实现,但使用函数语法是可能的根据语法创建任何特殊处理。
像 String.class
的替代方法意味着每个类都有具有字段类
的随播对象。因此,有两个问题:
-
class
是一个关键字,问题,其中语法将需要一个特殊的情况下 - 如果你只创建
类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:
class
is a keyword, so that causes a problem where the syntax would require a special case for it- if you just create
class A
without a companion object, it's would be odd to be able to refer toA.class
, which would be like accessing the class field on the companionA
.
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屋!