3

I have a trait "Foo" with some methods. I want to mix this trait to any class. But I dont want to write something like

val b = new Bar with Foo

I need something like where I just pass a class and it is mixed with Foo. I want to mix with this trait only i.e it is fixed that all classes should be mixed with Foo trait only.

val b = new Factory(Bar) //Factory returns instance with trait Foo

I found this post but I am not convinced.

Something like this is possible in scala?

Community
  • 1
  • 1
baba.kabira
  • 3,111
  • 2
  • 26
  • 37
  • Are you passing the _type_ `Bar` or an _instance_ of `Bar` in that factory example? If the latter, it is not possible, though implicit conversions are usually enough. – Daniel C. Sobral Nov 19 '10 at 20:15

1 Answers1

4

The current best solution is to implement Foo something like this:

class Foo(bar:Bar) {
    ...
}
object Foo {
    def apply(bar:Bar) = new Foo(bar)
    implicit def backToBar = this.bar
}

Then use it as

val foo = Foo(myBar)

For any method names that are shared between Foo and Bar, the version in Foo will be used (as with overloading in a mixin). Any other methods, the variant on Bar will be used.

The technique isn't perfect, methods in Bar will only ever call other methods defined in Bar, and never "overloads" defined in Foo. Otherwise, it's pretty close to your needs.

Kevin Wright
  • 49,540
  • 9
  • 105
  • 155
  • i am new to scala but above code in interactive scala shell does not works, other thing Bar is variable i.e it can be (Bar with Foo) or (Boo with Foo), I did not get the above code, what it exactly does – baba.kabira Nov 22 '10 at 11:11