Scalaz `Tag.apply`: How does it work?

Hi, I’m studying the book Advanced Scala, and I have some problems understanding this piece of code from the scalaz source:

object Tag {
  /** `subst` specialized to `Id`.
    *
    * @todo According to Miles, @specialized doesn't help here. Maybe manually specialize.
    */
  @inline def apply[@specialized A, T](a: A): A @@ T = a.asInstanceOf[A @@ T]

  // ...
}

How it works? a.asInstanceOf[A @@ T]should fail with a ClassCastException, right?

Usage example:

Multiplication(2) |+| Multiplication(3) 

In this case, ais Int, how can it be converted to @@[Int, Multiplication]( Tagged[Int, Multiplication])

Thanks for the help.

+4
source share
1 answer

This works due to erasure. @@It is a pure construction at the level of a level, that is, it has no representation at runtime.

A @@ T AnyRef{type Tag = T; type Self = A}. Int AnyRef ( java.lang.Integer java.lang.Object), .

{type Tag = T; type Self = A} , , JVM .

? @@ ( "qua" ) , , .

, , case class Multiplication(value: Int), Multiplication Int, Multiplication .

type Multiplication = Int, . Multiplication Int, .

Int @@ Multiplication Int, Int .

+12

All Articles