Implicit arguments: how to encode in function signature?

妖精的绣舞 提交于 2019-12-02 15:21:44

问题


Following the awesomely enlightening question by @TravisBrown concerning the enumeration of ADTs using shapeless, I am left with the following code snippet:

implicitly[EnumerableAdt[Foo]].values

I would like to encapsulate this within a method so that I don't have to .values after each invocation (It seems a cleaner API to me, that way). But I can't seem to get it right. Whenever I try to encapsulate the implicitly[EnumerableAdt[Foo]] I get implicit resolution errors.

What I had tried, that made most sense to me, was, for example:

def imply[T](implicit ev: T):Set[T] = implicitly[EnumerableAdt[T]].values

certainly without the ev made even less sense to me.

I am no expert in type level programming.


回答1:


If you look at the definition of implicitly[X], you can see that is requires an implicit argument of type X in scope. In your example, you have implicit ev: T in scope, which is not enough to call implicitly[EnumerableAdt[T]]! Try the following definition instead:

def imply[T](implicit ev: EnumerableAdt[T]):Set[T] = ev.values


来源:https://stackoverflow.com/questions/43650265/implicit-arguments-how-to-encode-in-function-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!