没有隐式视图可用于部分应用的方法

Jaw*_*oah 3 scala implicit implicit-conversion

所以我有以下方法包装一个类似Seq的对象Option.

def noneIfEmpty[S <% Seq[_]](seq: S): Option[S] = {
  if (seq.isEmpty) None else Some(seq)
}
Run Code Online (Sandbox Code Playgroud)

我希望能够使用这种方法来转换包含在中的计算结果Try.说我这样做List[Int]:

scala> val tryList = Try(List(1,2,3))
tryList: scala.util.Try[List[Int]] = Success(List(1, 2, 3))
Run Code Online (Sandbox Code Playgroud)

我应该可以noneIfEmpty用来映射Try[List[Int]]到a Try[Option[List[Int]]].如果我使用匿名函数并明确地将列表传递给noneIfEmpty...,这可以正常工作

scala> tryList map (list => noneIfEmpty(list))
res1: scala.util.Try[Option[List[Int]]] = Success(Some(List(1, 2, 3)))
Run Code Online (Sandbox Code Playgroud)

...但是如果我尝试noneIfEmpty作为部分应用函数传递它会中断.

scala> tryList map noneIfEmpty _
<console>:40: error: No implicit view available from S => Seq[_].
              tryList map noneIfEmpty _
                          ^
Run Code Online (Sandbox Code Playgroud)

如果我缩小noneIfEmpty到只接受列表,它也可以正常工作:

scala> def noneIfEmptyList[A](list: List[A]): Option[List[A]] = noneIfEmpty(list)
noneIfEmptyList: [A](list: List[A])Option[List[A]]
Run Code Online (Sandbox Code Playgroud)
scala> tryList map noneIfEmptyList _
res2: scala.util.Try[Option[List[Int]]] = Success(Some(List(1, 2, 3)))
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?是否有某种类型的擦除伏都教在工作或什么?

Gab*_*lla 5

问题是视图绑定是隐式参数的语法糖,所以你的方法确实如此

def noneIfEmpty[S](seq: S)(implicit ev: S => Seq[_]): Option[S]
Run Code Online (Sandbox Code Playgroud)

遗憾的是,您无法部分应用采用隐式参数的方法,因为eta-expansion(即将方法转换为函数)的过程需要提前解决隐含.

最终你的问题减少到了这一点.