以下片段解释了我的困惑:
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.
Run Code Online (Sandbox Code Playgroud)
为什么 Fellow.type 与 Fellow (作为一种类型)不同我不明白为什么这两种类型不同,为什么 :t -v 返回 Fellow.type ?
写在这个小实验之后,我检查了 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.
Run Code Online (Sandbox Code Playgroud)
那么究竟是什么.type?它从何而来 ?它与其他的有什么不同...特性名称,类名称
foo.type对于任何foo表示单类型的foo,即,类型,其具有foo作为其唯一的实例。(或者,更准确地说,对于 的实例AnyRef,类型只有foo和null作为其实例。)请注意,在语法构造中foo.type,foo部分是一个值(更准确地说,是一个值的路径),而foo.type是一个类型。
另外,请记住,a 会case class自动生成同名的配套模块,即每当您编写
case class foo
Run Code Online (Sandbox Code Playgroud)
还有一个隐含的
object foo
Run Code Online (Sandbox Code Playgroud)
所以这里发生的事情是,当您认为您在询问class 的类型时foo,您实际上是在询问singleton object 的类型foo。根据定义,单例对象foo的类型是单例类型foo.type。
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |