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
...
}
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.
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();
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With