Trait or Class that requires an implicit in order to exist?

So I find myself with code that has something like this:

trait Helper[T] { def canMakeA:T }

trait A

class Example extends A{
}

object Example {
  implicit val myHelper extends Helper[Example] 
}

The point of which is that I'll always need a Helper[A] object when something is working with trait A (it's extended classes). And this is simple enough to declare in a receiving function or class:

class Runner[T<:A:Helper] {   //T <: A and Helper[T] implicitly exists
... implicitly[Helper[T]] ...
}

However, I'm wondering if I can just bind trait A (and it's various descendant classes) to this requirement in the first place. Something like:

trait A:Helper {  //INCORRECT - EXAMPLE ONLY

}
class Runner[T<:A] {    //not necessary to use A:Helper, already implied as defined in A
    ... implicitly[Helper[T]] ...
    }

Is Scala somehow capable of this? Thanks!

OK so just to clarify, I'm simply stating that class A and Helper[A] must exist at all times because I need the implicit object to build objects of class A. Can you define class A in such a way that the implicit Helper[A] must exist..

I suppose this would work, but is there a more idiomatic way? Thank you

trait A[T<:A:Helper] {

}

class B extends A[B]{

}

object B{ define implicit Helper here.. }


If I understand your question correctly, that you always wish to have a helper available when working with A and not not sometimes (for which you have implicits as mentioned in the first example), then how about:

trait A extends Helper[A]{
   def canMakeA:A = //
}

This does exactly solve the purpose.

链接地址: http://www.djcxy.com/p/82696.html

上一篇: 不可变类中的方法继承

下一篇: 为了存在而需要隐含的特质或类?