隐式参数:如何在函数签名中编码?

时间:2017-04-27 06:34:54

标签: scala typeclass shapeless

在@TravisBrown关于使用无形的ADT枚举的令人敬畏的question之后,我留下了以下代码片段:

implicitly[EnumerableAdt[Foo]].values

我想在一个方法中封装它,这样我在每次调用后都不需要.values(这对我来说似乎是一个更干净的API)。 但是我似乎无法做对。每当我尝试封装implicitly[EnumerableAdt[Foo]]时,我都会得到隐式解析错误。

我曾经尝试过的,对我来说最有意义的是,例如:

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

当然,ev对我来说没有任何意义。

我不是类型级编程方面的专家。

1 个答案:

答案 0 :(得分:1)

如果你看一下implicitly[X]的定义,你可以看到在范围内需要一个类型为Function FnImageInsert(strCompleteImagePath) ' This code would be correct if you run Word from Excel Dim objWord As Word.Application Dim objDoc As Word.Document Dim objSelection As Word.Object ' If you run this code from Word you don't need to declare ' the application and the objects don't need to specify Word ' Dim objDoc As Document ' Dim objSelection As Object Dim Shp As Shape ' omit this object if you run this code from within Word Set objWord = CreateObject("Word.Application") Set objDoc = objWord.Documents.Open("C:\test\testimage.docx") ' it's the window you can make visible, not the application ' the application is always invisible ' objWord.Visible = True ' Selection Class: This looks like a little code from VB (this is VBA) ' I don't know if this actually works. I never saw this before. ' in fact, there is one "Selection" in Word which is the currently ' selected range in the ActiveDocument Set objSelection = objWord.Selection ' However, since you already have the 'Selection' object, why do you need ' a copy of it in 'objSelection'? ' the parentheses are superfluous here: objSelection.TypeText (vbCrLf & "One Picture will be inserted here...." & vbCrLf) ' Having a problem below... I get Object required error (424) ' Of course: Shp is a Shape (see the Dim statement) ' You are adding an InlineShape and assigning it to Shp, which cuses the error Set Shp = ActiveDocument.InlineShapes.AddPicture(FileName:=strCompleteImagePath, SaveWithDocument:=True).ConvertToShape ' If you wish to convert the Inlineshape to Shape, you should do this ' by setting the WrapText property after creation. ' But why not create a shape rightaway, if you don't want an InlineShape? ' You can't "Close" the Selection object ' In fact, there always is a selection while the document is open ' and all you can do is move it or dete4rmine its size. ' Close objSelection End Function 的隐式参数。在您的示例中,您在范围内有隐式X,这不足以调用ev: T!请改为尝试以下定义:

implicitly[EnumerableAdt[T]]