English 中文(简体)
摘要班/职务
原标题:Abstract classes/traits and invariant functions

海峡<代码>

trait T {
  def v: Int
  def +(t: T): T
}

缩略语

case class A(v: Int) extends T {
  def +(a: A) = A(v + a.v)
}

is not a valid subtype of T. The implementation of A.+ is too restrictive, because it only accepts elements of type A whereas the signature of T.+ requires all implementations to be able to accept objects of type T and not just objects of type A. So far, so reasonable.

如果我允许实施<代码>T,则限制性的I可修改<代码>/code>和A的声明如下:

trait T[This <: T[This]] {
  def v: Int
  def +(t: This): This
}

case class A(v: Int) extends T[A] {
  def +(a: A) = A(v + a.v)
}

这显然炸毁了签字类型。

是否有另一种方式宣布实施<代码> T 只需要与自己类型的物体相容?

1st EDIT http://stackoverflow.com/questions/4438507/abstract-classes-traits-and-invariant-Functions/4438883#4438883" 页: 1

虽然自发型的确缩短了目前的签名,但它们并没有缩短出现<代码>T的其他签名,例如:

trait C[D <: T[D], S] { self: S =>
  def +(perm: D): S
  def matches(other: S): Boolean
}
最佳回答

你们可以使用自我类型:

trait T[S] {
  self:S => 
  def v: Int
  def +(t: S): S
}

case class A(v: Int) extends T[A] {
  def +(a: A) = A(v + a.v)
}
问题回答

你们可以与哪类成员打交道。 我不知道你在此之后的“ort子”是什么品牌。 有一些多余之处,但另一方面,没有任何类型的参数给你带来大量节省。

trait TT {
  type This <: TT
  def v: Int
  def +(t: This): This
}
case class AA(v: Int) extends TT {
  type This = AA
  def +(a: This) = AA(v + a.v)
}




相关问题
Subclass check, is operator or enum check

A couple of friends was discussing the use of inheritance and how to check if a subclass is of a specific type and we decided to post it here on Stack. The debate was about if you should implement a ...

C++ Class Inheritance problem

Hi I have two classes, one called Instruction, one called LDI which inherits from instruction class. class Instruction{ protected: string name; int value; public: Instruction(string ...

Overloading a method in a subclass in C++

Suppose I have some code like this: class Base { public: virtual int Foo(int) = 0; }; class Derived : public Base { public: int Foo(int); virtual double Foo(double) = 0; }; ...

Embedding instead of inheritance in Go

What is your opinion of this design decision? What advantages does it have and what disadvantages? Links: Embedding description

Extending Flex FileReference class to contain another property

I want to extend the FileReference class of Flex to contain a custom property. I want to do this because AS3 doesn t let me pass arguments to functions through event listeners, which makes me feel sad,...

Interface Inheritance in C++

I have the following class structure: class InterfaceA { virtual void methodA =0; } class ClassA : public InterfaceA { void methodA(); } class InterfaceB : public InterfaceA { virtual ...

热门标签