本文介绍了从数组到列表的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写从Array[_]List[_]类型的隐式转换?我尝试了以下操作,但似乎不起作用.

How do I write an implicit conversion from Array[_] to List[_] type? I tried the following but it doesn't seem to work.

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

似乎可以正常工作.我的猜测是,在Predef中已经有一个genericArrayOps具有从Array[T] -> ArrayOps[T]隐式转换的签名,ArrayOps[T]具有方法.toList(): List[T].您的方法具有签名Array[T] -> List[T],这也使方法.toList[T]可用.主体要求使用该签名进行隐式转换.编译器不知道使用arrayToList会使该方法陷入无限循环,从而导致歧义错误.但是,类型推断返回类型似乎可以解决此问题.隐式解析似乎与类型推断并不一致.

Seems to work as expected. My guess is that there's already a genericArrayOps in Predef that has the signature for implicit conversion from Array[T] -> ArrayOps[T], ArrayOps[T] has a method .toList(): List[T]. Your method has the signature Array[T] -> List[T], which also makes the method .toList[T] available. The body is asking for an implicit conversion with that signature. The compiler doesn't know that using arrayToList will make that method go into an infinite loop, hence the ambiguity error. However, type-inferencing the return type seems to be able to work around this problem. Implicits resolution don't jive very well with type-inference it seems.

另外值得注意的是,由于默认情况下已经存在隐式转换,它将为您提供所需的内容,因此无需进行从ArrayList的隐式转换.

Also worth noting is that since there is already an implicit conversion that will get you what you want by default, there's no need to have an implicit conversion from Array to List.

这篇关于从数组到列表的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-09 22:16