2017-04-18 51 views
2

你如何定义一个Scala方法,使它能够在不引发编译错误的情况下接受任何类型A的子类?如何定义scala方法的上限

trait A 
case class B extends A 
case class C extends A 
case class W[T](abc: Option[T]= None) 

def methodOne(a: A): W[A] = { 
    a match { 
    case b:B => methodTwo() // throws compilation error 
    case c:C => methodThree() // throws compilation error 
    } 
} 
def methodTwo(): W[B] = y 
def methodThree(): W[C] = z 

试过类似

def methodOne[T <: A](a: A): W[T] 

,但它不允许编译仍然

回答

2

如果你想FORALL T <: A暗示W[T] <: W[A],你需要W协:

case class W[+T](abc: Option[T] = None) 

object X { 
    def methodOne(a: A): W[A] = { 
    a match { 
     case b: B => methodTwo() 
     case c: C => methodThree() 
    } 
    } 

    def methodTwo(): W[B] = ??? 
    def methodThree(): W[C] = ??? 
} 

方差的基本内容,请参阅this post

+0

谢谢!这工作... – Stanley

2

你需要让W协变。您可以通过它定义为W[+T]容易做到这一点:

case class W[+T](abc: Option[T] = None) 

这样,如果BA一个亚型,W[B]也是W[A]亚型。

Option例如定义为Option[+T],因此Option[B]Option[A]的子类型。

您可以检出the official scala docs了解更多详情