如何编写隐式转换Array[_]
to List[_]
类型?我尝试了以下方法,但似乎不起作用。
scala> implicit def arrayToList[A : ClassManifest](a: Array[A]): List[A] = a.toList
<console>:5: error: type mismatch;
found : Array[A]
required: ?{val toList: ?}
Note that implicit conversions are not applicable because they are ambiguous:
both method arrayToList in object $iw of type [A](a: Array[A])(implicit evidence$1: ClassManifest[A])List[A]
and method genericArrayOps in object Predef of type [T](xs: Array[T])scala.collection.mutable.ArrayOps[T]
are possible conversion functions from Array[A] to ?{val toList: ?}
implicit def arrayToList[A : ClassManifest](a: Array[A]): List[A] = a.toList
^
implicit def arrayToList[A](a: Array[A]) = a.toList
似乎按预期工作。我的猜测是已经有一个genericArrayOps
in Predef
具有隐式转换的签名Array[T] -> ArrayOps[T]
, ArrayOps[T]
有一个方法.toList(): List[T]
。你的方法有签名Array[T] -> List[T]
,这也使得该方法.toList[T]
可用的。主体要求使用该签名进行隐式转换。编译器不知道使用arrayToList
将使该方法进入无限循环,因此出现歧义错误。然而,类型推断返回类型似乎能够解决这个问题。隐式解析似乎与类型推断不太相符。
另外值得注意的是,由于已经有一个隐式转换可以默认为您提供所需的内容,因此无需从Array
to List
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)