0

I have case classes BFile and AFile that both extend trait File. And case classes BDir and ADir that both extend trait Dir. The classes are instantiated as their trait type.

I am trying to write implicit move methods (located on an object outside the A/BFile and A/BDir classes) that are overloaded for each combination of A/BFile & A/BDir.

I am unsure how to do this such that a different .move method will be implicitly used based on the specific classes of File and Directory. Is this even possible?

The reason why I don't want these methods implemented inside the class is because it requires me to pull in additional dependencies to use the classes; and I am unable to always provide these dependencies.

I also don't want to settle for depending on only the class since I am trying to follow the dependency inversion principle.

Edit: I think I am looking for the following or some equivalent:

trait File {
  ...
  def move(directory: the class implementing this that extends Dir): File
  def copy(directory: the class implementing this that extends Dir): File
}

trait Dir {
  ...
}
user unknown
  • 35,537
  • 11
  • 75
  • 121
Mike
  • 961
  • 6
  • 19
  • 43
  • When the compiler encounters a type inconsistency it will look to see if there is an implicit in scope that will solve the problem. If it finds one, _and only one_, the implicit is applied and compilation continues. For your scheme to work it sounds like you might need to study the implicit scoping rules to figure out where to "hide" each implicit such that it is the only one in scope to resolve each `.move` method. – jwvh Mar 09 '18 at 07:11
  • To do that it seems that I'd have to specify that the function takes a trait that is extended by a specific class. – Mike Mar 09 '18 at 15:54
  • So File and Dir are not sealed, is that right? And which is whoms trait? Is there some fallback from AFile to File planned, if no matching move method for AFile is in scope? – user unknown Mar 09 '18 at 16:40
  • They aren't sealed. Not completely sure what you mean by "And which is whoms trait?". The trait does not implement any methods currently. – Mike Mar 09 '18 at 16:48

0 Answers0