In Scala, a class and an object can be companion(same name, same file)
I came across Scala source code, with a file having a trait and object defined in it and both having same name, but object is not extending trait.
Is this style ok?
An object with the same name as a class is called a companion object. Conversely, the class is the object's companion class. A companion class or object can access the private members of its companion. Use a companion object for methods and values which are not specific to instances of the companion class.
Traits are similar in spirit to interfaces in Java programming language. Unlike a class, Scala traits cannot be instantiated and have no arguments or parameters. However, you can inherit (extend) them using classes and objects.
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.
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.
Yes, In both the case trait or object same name object become a companion object you can see below code you can access private members in class and trait both situations
trait
trait Simple {
private def line = "Line"
}
object Simple {
val objTrait = new Simple{}
def lineObj=objTrait.line
}
Simple.lineObj
class
class Simple {
private def line = "Line"
}
object Simple {
val objTrait = new Simple{}
def lineObj=objTrait.line
}
Simple.lineObj
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