autowire
autowire copied to clipboard
Nested traits
Hi
I'm not sure if I should classify this as general advice, a bug or a feature request, but here goes:
I've just tried creating an API of nested traits. The reason I wanted this is to avoid having multiple routers on the server side and multiple clients on the client side while still "namespacing" the API and therefore avoid putting all methods in the same trait. I figure it's less messy. Anyway, here's some example code:
trait Calculator {
def add(a: Int, b: Int): Int
def slowAdd(a: Int, b: Int): Future[Int]
trait Multiplication {
def times(a: Int, b: Int): Int
def slowTimes(a: Int, b: Int): Future[Int]
}
def multiplication: Multiplication
}
object CalculatorImpl extends api.Calculator {
def add(a: Int, b: Int): Int = a + b
def slowAdd(a: Int, b: Int): Future[Int] = Future.successful(a + b)
object multiplication extends Multiplication {
def slowTimes(a: Int, b: Int): Future[Int] = Future.successful(a * b)
def times(a: Int, b: Int): Int = a * b
}
}
This fails compiling:
[error] /home/alen/projects/skim/jvm/app/controllers/Api.scala:22: api.CalculatorImpl.multiplication.type does not take parameters
[error] val calculator = Server.route[Calculator](CalculatorImpl)
So, the questions here are:
- Should I not bother and just have multiple clients for each distinct API?
- What is the parameter that is trying to get passed?
- Is this a potential feature in the future?
- Is this a bug?
Cheers, Alen
My current feeling is that you should have multiple top-level traits:
package calculator
trait Adder {
def add(a: Int, b: Int): Int
def slowAdd(a: Int, b: Int): Future[Int]
}
trait Multiplication {
def times(a: Int, b: Int): Int
def slowTimes(a: Int, b: Int): Future[Int]
}
It's basically the same...
Japp, non nested traits works fine. Then combine the taits and the implementations if you want using cake pattern.