簡體   English   中英

這是Scala專業人士的錯誤嗎?

[英]Is this a bug of scala's specialized?

下列代碼編譯失敗,但如果我在方法dot刪除specialized注釋,則該代碼將通過。

Scala代碼運行程序版本2.12.0-RC2-版權所有2002-2016,LAMP / EPFL和Lightbend,Inc.

abstract class Op[@specialized Left, @specialized Right] {
  @specialized
  type Result

  def r: Numeric[Result]
  def times(left: Left, right: Right): Result
}


object Op {

  implicit object IntDoubleOp extends Op[Int, Double] {
    type Result = Double
    val r = implicitly[Numeric[Double]]
    def times(left: Int, right: Double): Double = left * right
  }
}


object calc {

  def dot[@specialized Left, @specialized Right](xs: Array[Left], ys: Array[Right])
          (implicit op: Op[Left, Right]): op.Result = {
    var total = op.r.zero
    var index = xs.length
    while(index > 0) {
      index -= 1
      total = op.r.plus(total, op.times(xs(index), ys(index)))
    }
    total
  }
}

test.scala:31: error: type mismatch;
 found   : op.Result
 required: op.Result
    total
    ^
one error found

這是沒有運氣的另一種嘗試:

//cat Ops.scala 
import scala.{ specialized => sp }

trait OpsResult {
  type N
}

trait SymOps extends OpsResult {
  @sp override type N
  def zero: N
  def plus(left: N, right: N): N
}

trait AsyOps[@sp L, @sp R] extends OpsResult {
  @sp override type N
  def times(left: L, right: R): N
}

trait MixOps[@sp L, @sp R] extends AsyOps[L, R] with SymOps

object MixOps {
  trait DoubleOps extends SymOps {
    override type N = Double
    def zero: Double = 0.0
    override def plus(left: Double, right: Double): Double = left + right
  }
  trait IntDoubleOps extends AsyOps[Int, Double] {
    override type N = Double
    override def times(left: Int, right: Double): Double = left * right
  }

  implicit object MixIntDouble extends IntDoubleOps with DoubleOps
}

object Test {
  def dot[@sp L, @sp R](xs: Array[L], ys: Array[R])
         (implicit op: MixOps[L, R]): op.N = {
    op.zero
  }
}

$ scalac Ops.scala 
Ops.scala:36: error: type mismatch;
 found   : op.N
 required: op.N
    op.zero
       ^
one error found

這是一個錯誤(也在2.11.x上重現)。 我已經聯系了LightBend的人員,這對於專門化和依賴於路徑的類型的代碼生成絕對是一個怪癖。 我將其范圍縮小到一個很小的復制:

trait M[@specialized T] {
  type Res
  def res: Res
}

object Test {
  def m[@specialized T](op: M[T]): op.Res = op.res
}

op的符號將不同步,並且不會如您在代碼中看到的那樣進行編譯。 @AdriaanMoors 已打開一個有關此問題的錯誤

Adriaan還向我指出了Aleksandar Prokopec的這篇博客文章 ,指出了@specilization代碼生成中的一些怪癖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM