如果你的要求是爲返回的上下文實例的類型的一些實例作爲簡單...即this
那麼你可以做到這一點,
class A() {
def omg(s: String): this.type = new A()
}
如果的傳承參與,
trait A {
type omgType
def omg(s: String): omgType
}
class B() extends A {
override type omgType = this.type
override def omg(s: String): omgType = new B()
}
class C() extends A {
override type omgType = this.type
override def omg(s: String): omgType = new C()
}
但是,如果你想要更多的普遍性,那麼你可能需要閱讀以下內容並應用它在那裏,
最簡單的方法是從magnet pattern
中獲取靈感,這是在噴霧中大量使用的。
我們可以藉助靈感來構建我們的定製解決方案,請記住它既不是pure magnet pattern
也不是path dependent type
的方法。它是一個混合的混合雞尾酒。
因此...可以說你想讓你的def process
能夠支持Int
和String
類型的輸入參數,並最終返回相應的結果。
您需要定義隱含的磁鐵,這些類型,
trait ProcessMagnet {
type Input
type Result
def input: Input
def process: Result
}
object ProcessMagnetProvider {
implicit def stringToStringProcessMagnet(string: String): ProcessMagnet = new ProcessMagnet {
override type Input = String
override type Result = String
override def input: Input = string
// define this for your doing...
override def process: Result = input + "_omg"
}
//... add for all your inputs
implicit def intToIntProcessMagnet(int: Int): ProcessMagnet = new ProcessMagnet {
override type Input = Int
override type Result = Int
override def input: Input = int
// define this for your doing...
override def process: Result = input + 1
}
}
def process[T](t: T)(implicit pmConverter: T => ProcessMagnet): ProcessMagnet = pmConverter(t)
// now just import our implicit magnets...
import ProcessMagnetProvider._
val intResult: Int = process(5).process.asInstanceOf[Int]
val stringResult: String = process("omg").process.asInstanceOf[String]
嘗試的[要麼](HTTP:// www.scala-lang.org/api/2.12.0/scala/util/Either.html):'Type1,Type2]' –
type1和type2之間是否有任何關係? – mfirry
你可以閱讀'磁鐵圖案'或'路徑依賴類型' –