简体   繁体   中英

In Scala, combine objects methods as class methods

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
  ...
}

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
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM