How do I give global access to an object in Scala without making it a singleton or passing it to everything? -


i have logger class logs events in application. while need 1 instance of logger in application, want class reusable, don't want make singleton , couple specific needs application.

i want able access logger instance anywhere in application without having create new 1 every time or pass around every class might need log something. have applicationutils singleton use point of access application's logger:

object applicationutils {     lazy val log : logger = new logger() } 

then have loggable trait add classes need logger:

trait loggable {     protected[this] lazy val log = applicationutils.log } 

is valid approach trying accomplish? feels little hack-y. there better approach using? i'm pretty new scala.

be careful when putting functionality in objects. functionality testable, if need test clients of code make sure interact correctly (via mocks , spies), you're stuck 'cause objects compile final classes , cannot mocked.

instead, use pattern:

trait t { /* code goes here */ }  object t extends t /* pass client code main sources */ 

now can create mockito mocks / spies trait t in test code, pass in , confirm interactions of code under test trait t code should be.

if have code that's client of t , interactions don't require testing, can directly reference object t.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -