[英]Scala bound on part of a type parameter
我有一個帶有類型參數的類,我希望該類上的方法僅限於遵循該參數化參數的參數。 但是,當具體實例化該類時,類型參數具有其他特征,我想忽略該方法的其他特征。 具體來說:
trait X {def str = "X"}
trait X1 extends X {def str = "X1"}
trait X2 extends X {def str = "X1"}
trait Y
class Foo[A <: X] { def do(a:A) = a.str}
val f = new Foo[X1 with Y]
val x1 = new X1 {}
val x2 = new X2 {}
val y = new Y {}
// I want this to compile
f.do(x1)
// and these to not compile
f.do(x2)
f.do(y)
當前,這三個最終語句都不編譯,但是我想在Foo.do
方法上設置type參數,以便僅第一個語句編譯。 但是,我不知道如何從聲明中“提取” A
類型的適當部分。
我已經找到了一個解決方案,盡管它不是太優雅,而且我願意接受其他解決方案。 因為假設,我只打算在do
方法中使用X
上的方法(因為它們是該類型唯一可見的方法),所以可以使用隱式將輸入參數轉換為適當的類型,如下所示:
trait X {def str = "X"}
trait X1 extends X {override def str = "X1"}
trait X2 extends X {override def str = "X1"}
trait Y
trait X {def str = "X"}
implicit def x2xWy[Xt <: X](x:Xt):Xt with Y = x.asInstanceOf[Xt with Y]
class Foo[A <: X] { def doIt[A1](a:A1)(implicit toA:(A1 => A)) = toA(a).str}
// this compiles
f.doIt(x1)
// and these do not
f.doIt(x2)
f.doIt(y)
也就是說,這種方法在幾種方面仍然不是最優的,即我們需要在編譯時知道在運行時可能混入A
所有類型。 另外,還需要仔細管理隱式函數的范圍,以確保其不會泄漏到可能引起問題的情況中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.