Is there a way to "program to interface" in scala?
I am new in Scala. I have a "trait" in scala and many classes extending that trait. I am looking for a way on how to use the interface instead of the class directly.
Currently, I am doing :
val clazz = new MyClass()
where MyClass is extended from a trait.
I am looking for a way to return the interface as an instance from the factory mathods for generating classes. Is there a way?
You can always just request the type of the interface:
val clazz: MyInterf = new MyClass()
If you really want to hide the implementation, one approach is to create a companion for the trait:
trait MyInterf {
...
}
class MyClass extends MyInterf {
...
}
object MyInterf {
def create: MyIntef = new MyClass()
}
// calling code
val impl = MyInterf.create
Related
In Scala, a class and an object can be companion(same name, same file)
I came across Scala source code, with a file having a trait and object defined in it and both having same name, but object is not extending trait.
Is this style ok?
Yes, In both the case trait or object same name object become a companion object you can see below code you can access private members in class and trait both situations
trait
trait Simple {
private def line = "Line"
}
object Simple {
val objTrait = new Simple{}
def lineObj=objTrait.line
}
Simple.lineObj
class
class Simple {
private def line = "Line"
}
object Simple {
val objTrait = new Simple{}
def lineObj=objTrait.line
}
Simple.lineObj
A typical use case for object is for methods and fields that you would mark as static in Java, if that helps.
The object doesn't extend the trait / class, it accompanies it, hence the term companion object.
Given a class like:
class MyClass {
protected object MyObj { ... }
}
is it possible to write a trait that will permit exposing MyObj. E.g. with inheritance I could do the following:
class TestMyClass extends MyClass {
val getMyObj = MyObj
}
but I want to do this via a trait, something like the following which doesn't typecheck:
trait ExposeMyObj {
val getMyObj = MyObj // super.MyObj/this.MyObj don't work
}
and use it like:
class TestMyClass extends ExposeMyObj
Is it possible to reproduce the functionality in TestMyClass into a trait to expose the protected object, and if so how?
If you know that your trait will always be mixed in to an instance of MyClass (or a subclass), you can enforce the expectation with a self-type, and then access the object:
trait ExposeMyObj {
self: MyClass =>
val getMyObj = MyObj
}
Edit: an example of using this trait:
class TestMyClass extends MyClass with ExposeMyObj
val test = new TestMyClass
test.getMyObj // accesses MyObj defined in MyClass.
Edit 2: attempting to address #jbrown's comment (re: testing queries within repos) - I would look at doing something like the following - first, in each repo's file, add a trait for each repo holding the queries for that repo:
trait UserQueries { // you could look at making this protected, if you like
protected def query1(param: String) = List(param) // very silly implementation, but hopefully enough to make the point
... // other queries
}
class UserRepo extends UserQueries // Has (internal) access to those queries
Then in the test class file for a given repo:
class UserQueriesTester extends UserQueries with ScalaTest { // or whatever test framework you are using
// (public) tests to run - eg:
def testQuery1 = query1("test") should be (List("test"))
}
Parametrized components work well with the cake pattern as long as you are only interested in a unique component for each typed component's, example:
trait AComponent[T] {
val a:A[T]
class A[T](implicit mf:Manifest[T]) {
println(mf)
}
}
class App extends AComponent[Int] {
val a = new A[Int]()
}
new App
Now my application requires me to inject an A[Int] and an A[String], obviously scala's type system doesn't allow me to extends AComponent twice. What is the common practice in this situation ?
I think the AComponent doesn't need to be parameterized itself. So loose the type parameter and change this into
trait AComponent {
val aInt: A[Int]
val aStr: A[String]
class A[T](implicit mf:Manifest[T]) {
println(mf)
}
}
class App extends AComponent {
val aInt = new A[Int]()
val aStr = new A[String]()
}
if you want to be able to provide instances for Int and String
Scala companion objects are frequently proposed as object factories. They seem to work well for this in the production code, but what about inserting mock objects for testing? The companion object won't know about the mock object and therefore cannot instantiate it.
I'd like to do something like this:
class Foo {}
object Foo {
def create():Foo = new Foo()
}
class FooCreator(factory:Foo) {
def this() = this(Foo)
...
factory.create()
...
}
class FooMock extends Foo {}
object FooMock extends Foo {
def create():Foo = new FooMock()
}
// in a test
val fooCreator = new FooCreator(FooMock)
This won't work because a companion object cannot be extended. I'm forced to create a Factory trait for both companion objects to mixin:
trait FooFactory {
def create():Foo;
}
class Foo {}
object Foo extends FooFactory {
def create():Foo = new Foo()
}
class FooCreator(factory:FooFactory) {
def this() = this(Foo)
...
factory.create()
...
}
class FooMock extends Foo {}
object FooMock extends FooFactory {
def create():Foo = new FooMock()
}
// in a test
val fooCreator = new FooCreator(FooMock)
Is there a better way to do this? Creating the factory trait just feels wrong, since that's what the companion object is supposed to be good at. (Keep in mind that the Mock artifacts are only known to the test subsystem, so I can't solve the problem by letting object Foo create a FooMock instance - the common pattern in production code).
Use the apply method rather than the object as your factory, as detailed in the answers to my question How to use companion factory objects as strategy?
You might want to take a look at ScalaMock, a mocking framework for Scala that can (among other things) mock object creation (compiler invocation). This is exactly one of the problems it's intended to solve.
I've looked at example of logging in Scala, and it usually looks like this:
import org.slf4j.LoggerFactory
trait Loggable {
private lazy val logger = LoggerFactory.getLogger(getClass)
protected def debug(msg: => AnyRef, t: => Throwable = null): Unit =
{...}
}
This seems independent of the concrete logging framework. While this does the job, it also introduces an extraneous lazy val in every instance that wants to do logging, which might well be every instance of the whole application. This seems much too heavy to me, in particular if you have many "small instances" of some specific type.
Is there a way of putting the logger in the object of the concrete class instead, just by using inheritance? If I have to explicitly declare the logger in the object of the class, and explicitly refer to it from the class/trait, then I have written almost as much code as if I had done no reuse at all.
Expressed in a non-logging specific context, the problem would be:
How do I declare in a trait that the implementing class must have a singleton object of type X, and that this singleton object must be accessible through method def x: X ?
I can't simply define an abstract method, because there could only be a single implementation in the class. I want that logging in a super-class gets me the super-class singleton, and logging in the sub-class gets me the sub-class singleton. Or put more simply, I want logging in Scala to work like traditional logging in Java, using static loggers specific to the class doing the logging. My current knowledge of Scala tells me that this is simply not possible without doing it exactly the same way you do in Java, without much if any benefits from using the "better" Scala.
Premature Optimization is the root of all evil
Let's be clear first about one thing: if your trait looks something like this:
trait Logger { lazy val log = Logger.getLogger }
Then what you have not done is as follows:
You have NOT created a logger instance per instance of your type
You have neither given yourself a memory nor a performance problem (unless you have)
What you have done is as follows:
You have an extra reference in each instance of your type
When you access the logger for the first time, you are probably doing some map lookup
Note that, even if you did create a separate logger for each instance of your type (which I frequently do, even if my program contains hundreds of thousands of these, so that I have very fine-grained control over my logging), you almost certainly still will neither have a performance nor a memory problem!
One "solution" is (of course), to make the companion object implement the logger interface:
object MyType extends Logger
class MyType {
import MyType._
log.info("Yay")
}
How do I declare in a trait that the
implementing class must have a
singleton object of type X, and that
this singleton object must be
accessible through method def x: X ?
Declare a trait that must be implemented by your companion objects.
trait Meta[Base] {
val logger = LoggerFactory.getLogger(getClass)
}
Create a base trait for your classes, sub-classes have to overwrite the meta method.
trait Base {
def meta: Meta[Base]
def logger = meta.logger
}
A class Whatever with a companion object:
object Whatever extends Meta[Base]
class Whatever extends Base {
def meta = Whatever
def doSomething = {
logger.log("oops")
}
}
In this way you only need to have a reference to the meta object.
We can use the Whatever class like this.
object Sample {
def main(args: Array[String]) {
val whatever = new Whatever
whatever.doSomething
}
}
I'm not sure I understand your question completely. So I apologize up front if this is not the answer you are looking for.
Define an object were you put your logger into, then create a companion trait.
object Loggable {
private val logger = "I'm a logger"
}
trait Loggable {
import Loggable._
def debug(msg: String) {
println(logger + ": " + msg)
}
}
So now you can use it like this:
scala> abstract class Abstraction
scala> class Implementation extends Abstraction with Loggable
scala> val test = new Implementation
scala> test.debug("error message")
I'm a logger: error message
Does this answer your question?
I think you cannot automatically get the corresponding singleton object of a class or require that such a singleton exists.
One reason is that you cannot know the type of the singleton before it is defined. Not sure, if this helps or if it is the best solution to your problem, but if you want to require some meta object to be defined with a specific trait, you could define something like:
trait HasSingleton[Traits] {
def meta: Traits
}
trait Log {
def classname: String
def log { println(classname) }
}
trait Debug {
def debug { print("Debug") }
}
class A extends HasSingleton[Log] {
def meta = A // Needs to be defined with a Singleton (or any object which inherits from Log}
def f {
meta.log
}
}
object A extends Log {
def classname = "A"
}
class B extends HasSingleton[Log with Debug] { // we want to use Log and Debug here
def meta = B
def g {
meta.log
meta.debug
}
}
object B extends Log with Debug {
def classname = "B"
}
(new A).f
// A
(new B).g
// B
// Debug