4

一部のケースオブジェクトに「r0」、「r1」などの名前を付けると、コンパイルエラーが発生します。別の名前を使用すると、コードは期待どおりにコンパイルおよび実行されます。その理由は大歓迎です!

コード:

package qndTests2

sealed abstract case class Reg()
trait RReg
trait RRegNotPc extends RReg
trait LowReg extends RReg
sealed abstract case class LowRegClass() extends Reg with LowReg
sealed abstract case class RRegNotPcClass() extends Reg with RRegNotPc
case object R0 extends LowRegClass
case object R1 extends LowRegClass
case object R2 extends RRegNotPcClass
case object R3 extends Reg with RReg

sealed abstract case class Base()
trait T1
trait T2 extends T1
trait T3 extends T1
sealed abstract case class CaseClassT3() extends Base with T3
sealed abstract case class CaseClassT2() extends Base with T2
case object r0 extends CaseClassT3
case object r1 extends CaseClassT3
case object r2 extends CaseClassT2
case object r3 extends Base with T1

object test {
  def regToInt(r: RReg): Int = {
    r match{
      case R0 => 0
      case R1 => 1
      case R2 => 2
      case R3 => 3
    }
  }
  def toInt(r: T1): Int = {
    r match{
      case r0 => 0
      case r1 => 1   //error: unreachable code
      case r2 => 2   //error: unreachable code
      case r3 => 3   //error: unreachable code
    }
  }
  def main(args: Array[String]): Unit = {
    println(toInt(r0))
    println(toInt(r1))
    println(regToInt(R0))
    println(regToInt(R3))
  }
}

パッケージ「qndTests2」には、Test.scalaという1つのファイルのみが含まれており、ファイルの全内容は上記のとおりです。「r0」〜「r3」を「A」〜「D」に置き換えるとコンパイルされます!理由はわかりません...私はとても疲れていて、明らかな何かを見落としていますか?

4

1 に答える 1

11

それはr0〜r3についてではなく、小文字と大文字についてです。この前の質問を参照してください。

それがバグであるか言語仕様の機能であるかにかかわらず、あなたの呼び出しはそこにあります、セクション8.1.1:

可変パターンxは、小文字で始まる単純な識別子です。これは任意の値と一致し、変数名をその値にバインドします。

于 2011-11-09T15:46:43.303 に答える