Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 764
Koziołek Avatar asked May 04 '11 11:05

Koziołek


People also ask

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 traits have companion 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.

Can a trait extend a object?

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.

How do you create an object for a trait?

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.


1 Answers

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.

like image 127
Peter Schmitz Avatar answered Oct 18 '22 18:10

Peter Schmitz