我有類似以下的東西......
class Base {
def doSomething = {...}
}
class B extends Base{
val text = "foo"
...
}
class C extends Base{
val value = "bar"
}
我想要一個方法,它接受任何擴展 Base 但保留其擴展屬性的類。我試過這個...
def myMethod[A extends Base](obj: A): Unit{
...
}
但這沒有用。如何創建允許此操作的方法?
uj5u.com熱心網友回復:
您正在尋找的概念是型別上限的概念。子型別關系的標準符號是<:。這個確切的符號也用于 Scala 語法中來表達型別邊界:
// upper type bound, `A` must be subtype of `U`,
// analogous to Java's "A extends U"
def foo[A <: U]: Unit = ???
// lower type bound, `A` must be supertype of `L`,
// analogous to Java's "A super L"
def bar[A >: L]: Unit = ???
// Both upper and lower bounds simultaneously:
def baz[A >: U <: L]: Unit = ???
在您的情況下,A應該是 的子型別Base,即它應該由Base上面的約束:A <: Base
def myMethod[A <: Base](obj: A): Unit{
...
}
來自 Java 時要記住的另一個重要區別是,在 Scala 中,您有可能使用站點差異和宣告站點差異。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/393579.html
