David S.
David S.

Reputation: 11168

How to use trait to add new method to class in Scala?

I have 3rd party class A:

class A {
  def methodA = ...
}

I want to use use trait to add a new method methodT to an instance of A

trait Atrait[...] {
  def methodT = {
    // how to get a reference of instance of type A?
  }
}

This methodT is specific to some situation, so I should use constraint in the trait. But I could not figure it out. Also, how can I invoke instance of A's method in a trait?

UPDATE

Trait doesn't work this way. See answer for alternative solution.

Upvotes: 0

Views: 198

Answers (1)

dhg
dhg

Reputation: 52681

This is the standard pattern for adding a method to a 3rd party class:

class A

implicit class ExtendedA(val a: A) extends AnyVal {
  def methodT: Unit = { println("called A.methodT") }
}

Then you can do:

val a = new A
a.methodT

Upvotes: 6

Related Questions