如何在函数签名中编码

如何在函数签名中编码

本文介绍了隐式参数:如何在函数签名中编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循极具启发性的问题 @TravisBrown 关于使用 shapeless 的 ADT 枚举,我留下以下代码片段:

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

我想将它封装在一个方法中,这样我就不必在每次调用后使用 .values (这样对我来说似乎是一个更清晰的 API).但是我似乎做对了.每当我尝试封装 implicitly[EnumerableAdt[Foo]] 时,我都会收到隐式解析错误.

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

当然没有 ev 对我来说更没有意义.

certainly without the ev made even less sense to me.

我不是类型级编程的专家.

I am no expert in type level programming.

推荐答案

如果看implicitly[X],你可以看到它需要一个 X 在范围内.在您的示例中,您在范围内具有隐式 ev: T,这不足以调用 implicitly[EnumerableAdt[T]]!请尝试以下定义:

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

这篇关于隐式参数:如何在函数签名中编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:32