简体   繁体   English

为什么在带有隐式参数的另一个方法上定义包装方法不起作用?

[英]Why defining a wrapping method over another method with an implicit argument doesn't work?

writing this fails type check: 编写此失败的类型检查:

val list = List(1,3,5,2,4)

list sortBy (i => -i) //this is ok

def wrappedSort[A,B](a: List[A])(by: A => B): List[A] = {
     a sortBy by
} // this fails type check

wrappedSort(list)(i => -i) //So this won't work either

We know the compile error is: No implicit Ordering defined for B. 我们知道编译错误是: No implicit Ordering defined for B.

To make it work I had to have the Wrapper method have the same implicit argument as the wrapped method's which is: 为了使其工作,我必须使Wrapper方法具有与包装方法相同的隐式参数,即:

import math.Ordering

def wrappedSort[A,B](a: List[A])(by: A => B)(implicit ord: Ordering[B]): List[A] = {
     a sortBy by
}

But this is quite annoying. 但这很烦人。 when working to abstract or extend over some library code, I come across some complicated context bounds that I must re-implement manually. 在尝试抽象或扩展某些库代码时,遇到了一些复杂的上下文边界,必须手动重新实现。 is there a workaround for this in which I don't have to specify the implicit argument in my own abstracions? 有没有一种解决方法,我不必在自己的摘要中指定隐式参数?

In this case, PreDef (which is in scope everywhere unless you specifically disable it in the compiler) there is an instance of Ordering[Int] available. 在这种情况下, PreDef (除非您在编译器中专门禁用它,否则它会处在范围内)有一个Ordering[Int]实例可用。 Hence, the compiler doesn't fail because it's in scope and it knows the exact implicit it has to search to find. 因此,编译器不会失败,因为它在范围内,并且知道必须搜索以找到的确切隐式。 When you provide an abstract B with that function signature, you effectively tell the compiler that B will not be supplied with an Ordering for all B (which is effectively every single type in the known universe) and the requirement that B have an Ordering as dictated by the sortBy function on List is failed immediately. 当您向抽象B提供该函数签名时,您实际上告诉编译器,将不会为B提供所有BOrdering (实际上是已知Universe中的每个单一类型),并且要求B具有所指示的Ordering List上的sortBy函数执行的操作立即失败。

There really isn't a way to avoid this nor should you want to avoid it at all. 确实没有一种方法可以避免这种情况,也根本不需要避免这种情况。 It's by design and a safety feature of the compiler. 这是设计使然,并且是编译器的安全功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM