Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala object and trait having same name

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?

like image 802
Mandroid Avatar asked Apr 09 '18 16:04

Mandroid


People also ask

Can I have a class and object with same name in a Scala file?

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.

Can we create object of trait in Scala?

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.

Can an object extend a trait Scala?

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.

What is class object and trait 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.


1 Answers

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
like image 112
Sandeep Purohit Avatar answered Oct 06 '22 06:10

Sandeep Purohit