有人可以解释type
关键字和#
运算符在 scala 中的工作原理以及如何使用它吗?请看例子。
//Example1
scala> type t1 = Option.type
defined type alias t1
//Shouldn't this work since previous example simply works?
scala> type t2 = String.type
<console>:7: error: type mismatch;
found : String.type
required: AnyRef
type t2 = String.type
^
//lets define custom trait T
scala> trait T
defined trait T
//... and obtain it's type like in Example1.
//Shouldn't this work since previous Example1 simply works?
scala> type t3 = T.type
<console>:7: error: not found: value T
type t3 = T.type
^
//Lets define some value of type T
scala> val v4 = new T{}
v4: T = $anon$1@5c3e8c76
//and obtain it's type (works)
scala> type t4 = v4.type
defined type alias t4
//this doesn't work
scala> type t4_1 = (new T{}).type
<console>:1: error: identifier expected but 'new' found.
type t4_1 = (new T{}).type
//as well as this (doesn't work)
scala> type t5 = "abc".type
<console>:1: error: identifier expected but string literal found.
type t5 = "abc".type
^
//but this compiles well
scala> val v6 = "abc"
v6: String = abc
scala> type t6 = v6.type
defined type alias t6
//lets create some values of created types:
scala> type t1 = Option.type
defined type alias t1
scala> val v1_1 = Some(10)
v1_1: Some[Int] = Some(10)
scala> type t7 = v1_1.type
defined type alias t7
scala> val v7:t7 = null
v7: t7 = null
scala> val v7_1:t7 = v1_1
v7_1: t7 = Some(10)
scala> val v7_2:t7 = Some(10)
<console>:9: error: type mismatch;
found : Some[Int]
required: t7
(which expands to) v1_1.type
val v7_2:t7 = Some(10)
^
//next let's try # operator
scala> class X[A,B](a:A,b:B)
defined class X
//doesn't work
scala> type xa = X[A,B]#A
<console>:8: error: not found: type A
type xa = X[A,B]#A
^
<console>:8: error: not found: type B
type xa = X[A,B]#A
^
//but such approach works:
scala> trait X2[C]{
type A
type B
val c:C
}
defined trait X2
scala> type xa2_1 = X2[String]#A
defined type alias xa2_1
scala> type xa2_2[M] = X2[M]#A
defined type alias xa2_2