Scala in depth 6 Scala的类型系统 中
Upper bound和Lower bound
用 :> 聲明 Lower bound,即父類約束, A :> B, A必須是B的父類
用 <: 聲明 Upper bound, 即子類約束, A <: B? A必須是B的子類
Lower bound的例子
package?ch6object?Test4?{println("Welcome?to?the?Scala?worksheet")class?A?{type?B?>:?List[Int]def?foo(a:?B)?=?a}val?x?=?new?A?{type?B?=?Traversable[Int]}Set(1)x.foo(Set(1))//?val?y?=?new?A?{?type?B?=?Set[Int]}?//?編譯錯(cuò)誤 }由此可見, A :> B的含義是: B的父類或與B有共同父類的類型
<:B通常不會用,因?yàn)樗?:B 的效果是一樣的
2. 高階類型
像高階函數(shù)一樣,有時(shí)一個(gè)類型需要另一個(gè)類型做參數(shù)。
?type?Callback[T]?=?Function1[T,?Unit]3.type lambda
類似與lambda 表達(dá)式表示的函數(shù), 類型也可以這樣靈活地定義,下面給出一個(gè)例子,這個(gè)例子來自
stackOverflow: http://stackoverflow.com/questions/8736164/what-are-type-lambdas-in-scala-and-what-are-their-benefits
4.對于一個(gè)高階類型A[T], A[T]的兼容性隨T的具體類型的變化有三種情況
假設(shè) S<: T
?(1)invariant? <=> ? A[S] 不兼容 A[T]
?(2) covariant <=>?? A[S] <: A[T]
?(3) contravariant <=> A[T] <: A[S]
原文:
A higher-kinded type that’s invariant implies that for any types T, A, and B if T[A] ?conforms to T[B] then A must be the equivalent type of B
T[A] conforms T[B]可以理解為 T[A]類型的引用可以賦給T[B]類型的對象
Covariance refers to the ability to substitute a type parameter with its parent type:
For any types T, A and B if T[A] ?conforms to T[B] ?then A <: B
5.mutable的類型必須是invariant的。 如Array
6.Function類型的參數(shù)類型,必須contraviriant的
package?ch6object?Test4?{println("Welcome?to?the?Scala?worksheet")???????//>?Welcome?to?the?Scala?worksheetdef?foo(x:?Any):String?=?"Hello,?I?received?a?"+?x//>?foo:?(x:?Any)Stringdef?bar(x:?String):?Any?=?foo(x)????????????????//>?bar:?(x:?String)Anybar("test")?????????????????????????????????????//>?res0:?Any?=?Hello,?I?received?a?testfoo("test")?????????????????????????????????????//>?res1:?String?=?Hello,?I?received?a?test }foo的類型為 Function1[Any, String]
bar的類型為 Function1[String, Any]
foo可以賦值給bar
轉(zhuǎn)載于:https://blog.51cto.com/dingbo/1596743
總結(jié)
以上是生活随笔為你收集整理的Scala in depth 6 Scala的类型系统 中的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: maven中文乱码问题——编译错误
- 下一篇: Windows Live Writer