2012-01-11 58 views
1

下面的代码重写-kinded更高的抽象类型示出了浅层级结构,其中表示一个一般的二进制操作的类型被用来在另一浅容器层次结构,以证实一个参数化的抽象类型:Scala中

trait BinaryOp[A] extends ((A,A) => A) 
trait Plus[A] extends BinaryOp[A] 
trait Minus[A] extends BinaryOp[A] 

trait BaseOps { 
    type T[A] <: BinaryOp[A] 
    def apply[B](one: B, two: B)(op: T[B]) = op(one, two) 
} 

case object PlusOp extends BaseOps { 
    override type T[A] = Plus[A] 
} 
case object MinusOp extends BaseOps { 
    override type T[A] = Minus[A] 
} 

object App { 
    val plus = new Plus[Int] { 
    def apply(i: Int, i2: Int) = i + i2 
    } 

    def main(a: Array[String]) { 
    val exp = Expr(PlusOp) 
    exp.bo(1,2)(plus) 
    } 
} 

的想法是能够预先说明可能对许多不同类型有效的操作,而不会受限于类型特定的操作。如果我一般定义表达式类,一切都很好

case class Expr[T <: BaseOps](bo: T = PlusOp) 

但是我使用情况下,它是不可取的表达式来进行paremeterized到:

case class Expr(bo: BaseOps = PlusOp) 

下面的代码失败,没有一个通用的Expr的:

object App { 
    val plus = new Plus[Int] { 
    def apply(i: Int, i2: Int) = i + i2 
    } 

    def main(a: Array[String]) { 
    val exp = Expr(PlusOp) 
    exp.bo(1,2)(plus) 
    } 
} 

错误:

found : App.plus.type (with underlying type java.lang.Object with Plus[Int]) 
required: exp.bo.T[Int] 
    exp.bo(1,2)(plus) 

这使得看起来好像来自抽象类型T[A] <: BinaryOp[A]的类型信息没有被子类型PlusOp中的信息证实,该信息覆盖抽象类型为T[A] = Plus[A]。有没有办法解决这个问题,而不使Expr通用?

回答

1

随着 “-Ydependent法类型”,

def Expr(_bo: BaseOps = PlusOp) = new BaseOps { 
    override type T[A] = _bo.T[A] 
    val bo: _bo.type = _bo 
} 

但是,我不知道这是什么意思恰恰...