autowire icon indicating copy to clipboard operation
autowire copied to clipboard

Nested traits

Open flashingpumpkin opened this issue 9 years ago • 2 comments

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:

  1. Should I not bother and just have multiple clients for each distinct API?
  2. What is the parameter that is trying to get passed?
  3. Is this a potential feature in the future?
  4. Is this a bug?

Cheers, Alen

flashingpumpkin avatar Jul 19 '15 11:07 flashingpumpkin

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...

lihaoyi avatar Jul 19 '15 13:07 lihaoyi

Japp, non nested traits works fine. Then combine the taits and the implementations if you want using cake pattern.

mkotsbak avatar Jul 19 '15 13:07 mkotsbak