Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  ...
}
like image 644
OlivierBlanvillain Avatar asked Jun 05 '13 17:06

OlivierBlanvillain


People also ask

What is the difference between class and object in Scala?

Difference Between Scala Classes and Objects Definition: A class is defined with the class keyword while an object is defined using the object keyword. Also, whereas a class can take parameters, an object can't take any parameter. Instantiation: To instantiate a regular class, we use the new keyword.

How do you create an object class in Scala?

In Scala, an object of a class is created using the new keyword. The syntax of creating object in Scala is: Syntax: var obj = new Dog();

What type of objects are the best uses for case classes?

Case classes work great for data transfer objects, the kind of classes that are mainly used for storing data, given the data-based methods that are generated. They don't work well in hierarchical class structures, however, because inherited fields aren't used to build its utility methods.

Can an object extend a trait?

Traits are used to share interfaces and fields between classes. They are similar to Java 8's interfaces. Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.


1 Answers

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
}
like image 77
dursun Avatar answered Sep 22 '22 16:09

dursun