5

I want to combine two libraries, one requires me to extend an abstract class with methods a_1 a_2 ... a_n, b_1, b_2 ... b_m, and the other one provides two objects A and B that respectively implement methods a_i and b_i. Is there an elegant way to combine A and B? Here is what I'm currently doing:

class myClass extends abstractClass {
  def a_1 = A.a_1
  def a_2 = A.a_2
  ...

  def b_1 = B.b_1
  def b_2 = B.b_2
  ...
}

2 Answers 2

4

scala supports multiple inheretence through traits but a class cannot be inhereted from an object

here is an example

object Combiner {
  trait A {
    def a_1 = println("Hello A a_1")
    def a_2 = println("Hello A a_2")
  }
  trait B {
    def b_1 = println("Hello B b_1")
    def b_2 = println("Hello B b_2")
  }
}
abstract class absractClass {
  def AC
}
class myClass extends absractClass with A with B {
  override def AC = println("AC from myClass")
}
def main(args: Array[String]) {
  var m = new myClass
  m.AC
  m.b_1
  m.b_2
  m.a_1
  m.a_2
}
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know you could write a trait inside a class/object. Thank you for the answer, it made my day :)
1

Something like this?

trait A {
  def a_1: Int
  def a_2: Int
  def foo = a_1 + a_2
}

trait B {
  def a_1 = 2
  def a_2 = 3
}

class C extends A with B

println((new C).foo)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.