值类实例化?

时间:2013-12-10 15:47:59

标签: scala

trait IntWrapper[@specialized(Long, Int) T] extends Any { 
  def value: T
  type I = Integral[T]
  implicit def leFromInt(i: Int)(implicit i2: I): T = i2.fromInt(i)
  implicit def leToInt(t: T)(implicit i2: I): Int = i2.toInt(t)

  def nums(implicit i: I) = {
    import i._
    @tc def inner(remaind: T, acc: List[Int]): List[Int] = quot(remaind, 10) match {
      case that if equiv(0, that) => rem(remaind, 10)::acc
      case that => inner(that, rem(remaind, 10)::acc)
    }
    inner(value, Nil)
  }
}
object Test {
  implicit class intw(val value: Int) extends AnyVal with IntWrapper[Int]
  def main(args: Array[String]): Unit = {
    println{
      3.nums
    }
  }
}

运行javap -c Test $ give

public void main(java.lang.String[]);
      Code:
         0: getstatic     #24                 // Field scala/Predef$.MODULE$:Lscala/Predef$;
         3: new           #26                 // class Test$intw
         6: dup           
         7: aload_0       
         8: iconst_3      
         9: invokevirtual #28                 // Method intw:(I)I
        12: invokespecial #31                 // Method Test$intw."<init>":(I)V
        15: getstatic     #36                 // Field scala/math/Numeric$IntIsIntegral$.MODULE$:Lscala/math/Numeric$IntIsIntegral$;
        18: invokevirtual #40                 // Method Test$intw.nums:(Lscala/math/Integral;)Lscala/collection/immutable/List;
        21: invokevirtual #44                 // Method scala/Predef$.println:(Ljava/lang/Object;)V
        24: return 

鉴于此

  

在以下情况下实际实例化值类:

     

将值类视为另一种类型。分配了一个值类   数组。进行运行时类型测试,例如模式匹配。

为什么要实例化intw?

1 个答案:

答案 0 :(得分:1)

nums方法未在intw中定义,而是在其父特征IntWrapper中定义,并且当您从特征中调用方法时,需要从值初始化继承值类。这是“值类被视为另一种类型”的实例。请参阅Scala网站上Value Classes and Universal Traits中的简介的最后部分和分配详细信息的第一部分。

在这种特殊情况下,可以消除初始化,但编译器目前还不够智能。在Value Classes proposal的末尾简要讨论了它。

相关问题