Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override function in trait

Tags:

scala

Let's say I have the following trait

trait Foo[T] {
  def overrideMe(other:Foo[T]) : Int
}

I would like to be able to do

class Bar extends Foo[Int] {
   override  def overrideMe(other:Bar) : Int = other.BarFn
}

but it does not compile. The reason is that I would like overrideMe to be able to use functionality of the subtype. I could do something like

class Bar extends Foo[Int] {
   override  def overrideMe(other:Foo[Int]) : Int = {
      other.asInstanceOf[Bar].BarFn
}

but that doesn't look very nice.

Is it possible to say in the trait that the virtual funcation can be overridden with a subtype?

edit @agilesteel That almost works, but I run into trouble if I have a function in another class relying only on the trait Foo

class Test[T] {
    def callOverrideMe(a : Foo[T], b : Foo[T] ) : Int = a.overrideMe(b)
}

I get a compile error: type mismatch; found b.type (with underlying type foo.Foo[T]) required a.SubType

like image 524
Fredrik Jansson Avatar asked Aug 22 '11 20:08

Fredrik Jansson


People also ask

What is trait function in PHP?

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

Can traits be extended?

Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.

Can a trait extend a class PHP?

Only classes can be extended. Traits are not classes. They can be used/included by classes but are not classes themselves.

Can a trait have a constructor PHP?

Unlike traits in Scala, traits in PHP can have a constructor but it must be declared public (an error will be thrown if is private or protected). Anyway, be cautious when using constructors in traits, though, because it may lead to unintended collisions in the composing classes.


1 Answers

trait Foo[T] {
  type TheSubType <: Foo[T]
  def overrideMe(other: TheSubType) : Int
}

class Bar extends Foo[Int] {
   type TheSubType = Bar
   override def overrideMe(other: Bar) : Int = other.barFn
   def barFn = 10
}
like image 194
agilesteel Avatar answered Oct 22 '22 11:10

agilesteel