ciembor
ciembor

Reputation: 7337

Composition in Scala, based on objects (singletons)

I want to make a composition with two objects. I can do it with objects nesting:

object Composition {
  object SomePartOfComposition {
    // some body
  }
}

But the body of SomePartOfComposition is such long, that I want it in a separate file. How can I do that?

// edit

I know, that I can use trait. But I want strict one to one relation - it is a singleton.

Upvotes: 1

Views: 268

Answers (3)

kassens
kassens

Reputation: 4475

You can have a strict one to one relationship when using traits by defining the self type of the trait to be the type of the object:

object Composition {
  object SomePartOfComposition extends SomePartOfCompositionTrait
}

trait SomePartOfCompositionTrait {
  this: Composition.SomePartOfComposition.type =>
  // body
}

Upvotes: 5

Rex Kerr
Rex Kerr

Reputation: 167901

You haven't specified why it matters that one object is nested in the other, so I assume that you just want the syntax to look like A.B. So:

//File A
object A {
  val B = C
}

// File C
object C {
  import A._
  // All your code, written just like it was placed inside A
}

If this is not what you want, please edit the question to explain all the criteria.

Upvotes: 5

Dave Griffith
Dave Griffith

Reputation: 20515

object Composition {
  object SomePartOfComposition extends SomePartTrait
}

trait SomePartTrait{
   //in it's own file
   //implement the body here
}

Upvotes: 5

Related Questions