[英]Difference between Class and Class.type in Scala
The following snippet explain my confusion:以下片段解释了我的困惑:
scala> case class fellow[A, B](name:A, age:B)
class fellow
scala> :t -v fellow
// Type signature
fellow.type
// Internal Type structure
TypeRef(
pre = ThisType(class $iw)
TypeSymbol(class fellow extends Serializable)
)
scala> :kind -v fellow.type
fellow.type's kind is A
*
This is a proper type.
scala> :kind -v fellow
fellow's kind is F[A1,A2]
* -> * -> *
This is a type constructor: a 1st-order-kinded type.
Why fellow.type is different than fellow (as a type) I don't get why those two type are different, and why :t -v returns fellow.type ?为什么 Fellow.type 与 Fellow (作为一种类型)不同我不明白为什么这两种类型不同,以及为什么 :t -v 返回 Fellow.type ?
Write after this little experiment i checked against List and saw that it was the same写在这个小实验之后,我检查了 List,发现它是一样的
scala> :kind -v List
List's kind is F[+A]
* -(+)-> *
This is a type constructor: a 1st-order-kinded type.
scala> :kind -v List.type
scala.collection.immutable.List.type's kind is A
*
This is a proper type.
So what is the .type
about exaxctly ?那么关于 exaxctly 的.type
是什么? Where does it come from ?它从何而来 ? how does it differ from the other ... Trait Name, Class name它与其他的有什么不同...特性名称,类名称
foo.type
for any foo
denotes the singleton type of foo
, ie the type which has foo
as its only instance. foo.type
任何foo
表示单类型的foo
,即其具有式foo
作为其唯一的实例。 (Or, more precisely, for instances of AnyRef
, the type which has only foo
and null
as its instances.) Please note that in the syntactic construction foo.type
the foo
part is a value (more precisely, a path to a value), whereas foo.type
is a type . (或者,更准确地说,对于AnyRef
实例,该类型只有foo
和null
作为其实例。)请注意,在语法构造foo.type
, foo
部分是一个值(更准确地说,是一个值的路径) ,而foo.type
是一个类型。
Also, remember that a case class
automatically generates a companion module of the same name, ie whenever you write另外,请记住, case class
自动生成同名的伴随模块,即每当您编写
case class foo
there is also an implicit还有一个隐含的
object foo
So what is happening here, is that when you think you are asking for the type of the class foo
, you are actually asking about the type of the singleton object foo
.所以这里发生的事情是,当您认为您在询问foo
类的类型时,您实际上是在询问单例对象foo
的类型。 And the type of the singleton object foo
is the singleton type foo.type
, by definition.根据定义,单例对象foo
的类型是单例类型foo.type
。
I'll just add that besides :t
in REPL you can use typeOf
in ordinary Scala code我将补充一点,除了:t
在 REPL 中,您还可以在普通 Scala 代码中使用typeOf
import scala.reflect.runtime.universe._
typeOf[fellow[_, _]].typeSymbol // class fellow
typeOf[fellow.type].typeSymbol // object fellow
ie a class and its companion object.即一个类和它的同伴对象。
For values you can also do对于值,您也可以这样做
def getType[A: TypeTag](a: A): Type = typeOf[A]
getType(fellow("a", 1)).typeSymbol // class fellow
getType(fellow).typeSymbol // object fellow
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.