1

Given traits:

trait HasSize {
  def size() : Int
}

trait StorageTrait extends HasSize {
  def something() : Unit
}

trait YetAnotherStorageTrait extends HasSize {
  def anotherSomething() : Unit
}

I want to create class

class InMemoryStorage extends StorageTrait with YetAnotherStorageTrait {
   //...
}

now, method size of StorageTrait returns different thing than method YetAnotherStorageTrait (it's still a size, but of different collections).

What is the correct way to design such case in Scala?

jdevelop
  • 12,176
  • 10
  • 56
  • 112

1 Answers1

1

If I understand the question correctly, you have a class which inherits traits which respond differently to the size method? Then there is no way to resolve this ambiguity than to use composition instead of mixin.

class InMemoryStorage
  def mainStorage: StorageTrait
  def auxStorage: YetAnotherStorageTrait

  def mainSize = mainStorage.size
  def auxSize  = auxStorage.size
}

Is that what you are looking after?

0__
  • 66,707
  • 21
  • 171
  • 266
  • not really, I am looking for a way to "bind" a method implementation to trait. So whenever the class is accessed through StorageTrait, one "size" is used, and if it's accessed through "YesAnotherStorageTrait" - another implementation is used. I'm ready to pay the penalty when it's not possible to call "size" on instance of InMemoryStorage type, because it doesn't make much sense. – jdevelop Jan 06 '13 at 11:32
  • 1
    That's not possible, you cannot "overload" a method with the same signature. If you mix-in both, you'll have to declare which one overrides the `size` method. If you want them to behave independently, you need to use a private size method; that still leaves the public size method ambiguous, so you should really not do this. What is the problem with the composition above -- if you call into `mainStorage`, that will correctly use its size, and for `auxStorage` that's true, too? – 0__ Jan 06 '13 at 11:41
  • 1
    Just stumbled [across this answer](http://stackoverflow.com/questions/1836060/cant-extend-two-traits-that-have-a-method-with-the-same-signature/1838214#1838214); although I still think composition is better, this may show you another possibility. – 0__ Jan 18 '13 at 17:32