In Scala Objects are singletons... so if I make:
trait SimpleTrait {
def setString(s: String): Unit = {
InnerTraitObject setString s
}
def getString(): String = {
return InnerTraitObject getString
}
object InnerTraitObject {
var str: String = ""
def setString(s: String): Unit = {
str = s
}
def getString(): String = {
return str
}
}
}
Then
class SimpleClass extends SimpleTrait{
/// empty impl
}
and:
object App {
def main(args: Array[String]): Unit = {
val a = new SimpleClass();
val b = new SimpleClass();
a.setString("a");
println("A value is " + a.getString());
println("B value is " + b.getString());
}
}
I would like to see
A value is a
B value is a
but i got
A value is a
B value is
My question is: If object is singleton then why if i put it into Trait then it behave like common object?
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.
A companion object is an object with the same name as a class or trait and defined in the same source file as the associated file or 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.
Defining a Trait for Common Behavior We create a trait object by specifying some sort of pointer, such as a & reference or a Box<T> smart pointer, then the dyn keyword, and then specifying the relevant trait.
It´s not a global singleton, it´s a singleton referring to the instance of the trait (which can have several instances). It depends where you define the singleton: if defined in a package then it´s singleton concerning the package and the package is singleton, too, so the object is singleton. You see, it depends on the context you are defining something as a singleton. If the context is singleton then the defined object too.
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