Koziołek
Koziołek

Reputation: 2874

Scala Object inside Trait

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?

Upvotes: 11

Views: 4072

Answers (1)

Peter Schmitz
Peter Schmitz

Reputation: 5844

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.

Upvotes: 21

Related Questions