简体   繁体   English

编译器无法解析默认类型的函数参数

[英]Compiler Not Resolving Default Typed Function Parameter

I have a function that takes a typed sort function as a parameter, and I want this sort function to have a default parameter: 我有一个将类型化排序函数作为参数的函数,并且我希望此排序函数具有默认参数:

def foo[T](sort: MyObject => T = _.position)(implicit o: Ordering[T])

MyObject.position returns an Int . MyObject.position返回一个Int

Understandably, I am getting this error: 可以理解,我收到此错误:

Expression of type (MyObject) => Int doesn't conform to expected type (MyObject) => T

OK, but I was hoping that the compiler would figure out that in the default case T is Int and check that an Ordering[Int] is available in implicit scope. 好的,但是我希望编译器能够找出默认情况下TInt并检查implicit范围中的Ordering[Int]是否可用。

How can I help the compiler resolve this? 我如何帮助编译器解决此问题?

You can use an overloaded function with and without an argument: 您可以使用带参数和不带参数的重载函数:

def foo(): FooResult = foo(_.position)
def foo[T](sort: MyObject => T)(implicit o: Ordering[T]): FooResult = ???

I can think up one way though, how to actually do it with a non-overloaded function (and some boilerplate). 我可以想出一种方法,即如何使用非重载功能(和某些样板)实际执行此操作。

You can take a special argument, which packs the sort function, the ordering and even the implementation of foo , and provide an implicit conversion from a suitable function to this argument. 您可以使用一个特殊的参数,该参数包装了sort函数, foo的顺序甚至实现,并提供了从合适的函数到该参数的隐式转换。 This is basically an application of the Magnet pattern . 这基本上是磁铁图案的一种应用。

sealed trait Magnet {
  type T

  val sort: MyObject => T
  implicit val o: Ordering[T] 

  def fooImpl = ???
}

object Magnet {
  implicit def fromSort[T0](sortArg: MyObject => T0)(implicit ordArg: Ordering[T0]): Magnet = 
    new Magnet {
      type T = T0

      val sort = sortArg
      val o = ordArg
    }
}

def foo(sort: Magnet = (_: MyObject).position) = sort.fooImpl

One drawback is that this loses the expected type for the argument, so you have to specify the type of the argument of the sort function. 一个缺点是,这会丢失参数的预期类型,因此您必须指定sort函数的参数sort

The usability for your case is questionable, but it's still an interesting solution nevertheless and may be useful in other situations. 您的案例的可用性令人怀疑,但它仍然是一个有趣的解决方案,在其他情况下可能很有用。

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

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