jeudi 23 novembre 2017

How to design a way to provide an implementation in Scala

I am designing a framework in scala. This framework will have 3 traits: A, B and C. In order to use it, the developer will extend those traits and provide an implementation. Then, he will call an execute() function which will use the implementations.

The problem is: I wont pass any instance to the execute function. That function should use the implementations provided as it needs them. I dont know how to do this.

My first idea was to create a class (which will contain that function) and it will receive as parameter 3 factory methods to create instances of those classes. The code would be something like this:

trait Abs{def f():Int}

case class Concr extends Abs{def f():Int = 8}    

case class Manager[A <: Abs](val factory: () => A){def exec():Int = {factory().f()}}

Manager[Concr]({() => Concr()}).exec() //It evaluates 8

The problem of this solution is it is dirty, as in the manager you have to refer to the factory every time you want to create an instance and I was trying to find a better way.

Aucun commentaire:

Enregistrer un commentaire