一般将SeqView强制为Sala,Sala 2.12

是否存在将SeqView强制为Seq的通用方法?

在Scala 2.12中,SeqView扩展了Seq,因此当您可能需要严格的集合时,您可能会变得懒惰。

我试图将SeqViews强制转换为Seqs,但是遇到了我不熟悉的类型错误:

import scala.collection.SeqView
def force(xs: Seq[Int]): Seq[Int] = xs match {
  case view: SeqView[_,_] => view.force
  case other              => other
}

force(List(1,2,3))
force(List(1,3).view)
Cannot construct a collection of type That with elements of type _ based on a collection of type _.

Scastie链接:https://scastie.scala-lang.org/ThMW8jixT7Odet17EiDavA

值得注意的是,我可以为比赛提供类型参数,但是,当然,我会收到类型擦除警告

import scala.collection.SeqView
def force(xs: Seq[Int]): Seq[Int] = xs match {
  case view: SeqView[Int,Seq[Int]] => view.force
  case other              => other
}

force(List(1,3).view)

类型删除警告使我感到恐惧,但这似乎起作用。

有人能对此有所启发吗?

yangyang103 回答:一般将SeqView强制为Sala,Sala 2.12

通过在patten匹配中使用Seq[_,_],使编译器无法找到类型类CanBuildFrom的隐式权限。

我想出的解决方法是,没有警告并允许编译器解析CanBuildFrom只是为了与SeqView[_,_]匹配,然后使用asInstanceOf返回原始类型:>

import scala.collection.SeqView

def force[A](xs: Seq[A]): Seq[A] = xs match {
    case view: SeqView[_,_]    => view.asInstanceOf[SeqView[A,Seq[A]]].force
    case other: Seq[A]          => other
}

println(force(List(1,2,3)))
println(force(List(1,3).view))

我还添加了类型参数A而不是固定的Int

另一种可能性是仅用@unchecked注释类型:

def force[A](xs: Seq[A]): Seq[A] = xs match {
    case view: SeqView[A@unchecked,Seq[A]@unchecked]   => view.force
    case other: Seq[A]          => other
}
本文链接:https://www.f2er.com/3162126.html

大家都在问