类型参数的子类型限制

时间:2015-02-28 03:07:30

标签: scala lift

假设有两个特征

trait LongKeyedRestricted[OwnerType <: LongKeyedRestricted[OwnerType]] {
    self: => OwnerType
}

trait LongKeyed[OwnerType] {
    self: => OwnerType
}

第一个特征定义是显式的,类型参数必须是LongKeyedRestricted [OwnerType]的子类型。但是,给定了一些User类的定义

class User extends LongKeyed[User]

我不是说User是LongKeyed [User]的子类型。我的问题是第一个特征定义中的额外限制是如何有用的,我找不到可以违反这个特性的用例。

注意

参考Liftweb

trait LongKeyedMapper[OwnerType <: LongKeyedMapper[OwnerType]] extends KeyedMapper[Long, OwnerType] with BaseLongKeyedMapper {
    self: OwnerType =>
}

1 个答案:

答案 0 :(得分:1)

嗯...它像LongKeyedRestricted一样确保它的类型参数是LongKeyedRestricted[ OwnerType ]的子类型,它确保某些属性在某些时候可能有用。

为了理解这一切,让我们考虑以下更简单的例子。

trait IntLike {
  def me: Int
}

trait IntLikeHandle[ IntLike ] {
  def myHandle: IntLike
}

trait IntLikeHandleStrict[ IntLike <: IntLikeHandle[ IntLike ] ] {
  def myHandle: IntLike
}

case class IntLikeHandleConcrete( handle: IntLike )
    extends IntLikeHandle[ IntLike ] {
  def myHandle = handle
}

case class IntLikeHandleConcreteOther( handle: IntLike )
    extends IntLike with IntLikeHandle[ IntLike ] {
  def me = handle.me
  def myHandle = handle
}

 // Note :: ClassQualityDisclaimer : This class achieves nothing
 // at all, and is just for demonstrating the possibilities.
case class IntLikeHandleStrictConcrete( handle: IntLikeHandleConcreteOther )
    extends IntLikeHandleStrict[ IntLike ] {
  def myHandle = handle.myHandle

  // this class allows you to do some cool things which were not
  // possible in class extending trait without restrictions.

  // Note :: MethodQualityDisclaimer : This method achieves nothing
  // at all, and is just for demonstrating the possibilities.
  def me = math.max( handle.me, myHandle.me )


}

注意:: CodeQualityDisclaimer:此代码完全没有任何效果,仅用于演示可能性。