gpt4 book ai didi

generics - Scala 的 implicit 可以组合成转换更高种类的类型吗?

转载 作者:行者123 更新时间:2023-12-01 23:15:27 25 4
gpt4 key购买 nike

假设我有一个名为 LongArrayWritable 的类型,它是 Long 数组的盒装表示。我有在这些类型之间转换的隐式定义:

implicit def boxLongArray(array: Array[Long]) : LongArrayWritable { /*elided*/}
implicit def unboxLongArray(array: LongArrayWritable) : Array[Long] { /*elided*/}

现在,我还有在 java.lang.Iterable 和 scala.collection.List[X] 之间以其通用形式进行转换的隐式:

implicit def iterator2list[X](it : java.lang.Iterable[X]) : List[X] { /* elided */ }
implicit def list2iterator[X](list : List[X]) : java.lang.Iterable[X] { /* elided */ }

根据这些定义,scala 编译器能否推断出 java.lang.Iterable[LongArrayWritable] 和 List[Array[Long]] 之间的隐式转换(相当于 iterator2list(iterator).map(unboxLongArray(_) )),或者这是否超出了隐式的能力,因此需要它自己的(显式?)隐式定义?

谢谢,

蒂姆

最佳答案

有一篇帖子涵盖了这个问题:How can I chain implicits in Scala? .本质上,您需要有一个 View 绑定(bind)到 LongArrayWritable 的转换。 .这意味着,隐式 def转换为 LongArrayWritable接收一个隐式参数(称为 View 绑定(bind)),以便此 def 的参数不直接是 Array但某些类型可以转换为 Array :

object LongArrayWritable {
implicit def fromArraySource[A <% Array[Long]](a: A): LongArrayWritable = apply(a)
}
case class LongArrayWritable(a: Array[Long])

def test(a: LongArrayWritable): Unit = println("OK")

现在这适用于数组:

test(Array( 1L, 2L, 3L))

然而,由于Array不是 Iterable并且没有来自 Iterable 的默认转换至 Array在范围内,您需要添加一个:

implicit def iterable2Array[A: ClassManifest](i: Iterable[A]): Array[A] = i.toArray

然后就可以了:

test(List(1L, 2L, 3L))

View 绑定(bind)A <% Array[Long]A => Array[Long] 类型的隐式参数的快捷方式, 所以你也可以写

implicit def fromArraySource[A](a: A)(implicit view: A => Array[Long]) ...

关于generics - Scala 的 implicit 可以组合成转换更高种类的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5485672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com