Dan Horne
Dan Horne

Reputation: 73

Recommended pattern for sharing common objects across classes in Scala

I'm just looking into Scala and I have a couple of questions regarding the best way to share common attributes like loggers, database handles and configuration across classes without passing them around.

We could make a singleton class which would have the logger, handle and application but this seems wrong to me since and any subclassing the singleton isn't a more specialised case.

I see that Scala has the concept of a trait which I believe is like a mixin. Is it possible - and good practice if it is - to combine a trait with a singleton? If not what is the recommended approach?

Upvotes: 0

Views: 876

Answers (2)

jacks
jacks

Reputation: 4783

This is a big subject and there is no single correct best approach - your question is quite broad. Here are some areas I would spend some time reading up on if you want to get the bigger picture:-

  • Mixin traits are a popular way of decorating classes with reusable behaviours - a custom logger being a good example. Assuming you really do need to customise a logging libraries behaviour that is.

  • For configuration and database connections, mixin traits work as well but some frameworks eg. Play use dependency injection as a way for classes to obtain their dependencies. Note that there are both compile time and runtime DI frameworks.

  • Another, less common, approach that is arguably more complex is to use aspects (AOP) - https://www.google.co.uk/search?ei=1iN-W6neNePWgAb05orYAQ&q=scala+aop&oq=scala+aop

If you are just starting out then choose some popular libraries - read their docs - and let them guide you as to how best to adopt them, eg.

Logging - https://github.com/lightbend/scala-logging
Config - https://github.com/lightbend/config

Upvotes: 1

Mansoor Baba Shaik
Mansoor Baba Shaik

Reputation: 492

The best practice to share common entities throughout the package is by declaring them in the package object file.

Refer here https://alvinalexander.com/scala/scala-package-objects-how-to-name-location-cookbook-recipe

Upvotes: 1

Related Questions