Search code examples
scalatraitscompanion-object

Can a trait guarantee that it is inherited by a companion object at compile- or run-time


I have a trait for which the initialization is not inherently thread-safe, but is intended strictly for use as a base for companion objects, for which initialization is thread-safe by definition.

Is there some way to guarantee (either at compile- or run-time) that the trait is always extended by a companion object? The trait has a method that is always and only called during companion-object initialization, which could be the site of the verification.


Solution

  • If the trait must be extended by exactly 1 object, you can check it at compiletime like this:

    trait Foo { this: Bar.type =>
      ...
    }
    
    object Bar extends Foo
    

    If you need several objects to extend it, you could try something based on the Singleton magical type:

    trait Foo { this: Singleton =>
      ...
    }
    

    but I don't know if that works.