scala - Understanding Tagged Types and asInstanceOf -


i use tagged types miles sabin gist:

type tagged[u] = { type tag = u } type @@[t, u] = t tagged[u]  trait mytrait  def tag(s: string): string @@ mytrait = s.asinstanceof[string @@ mytrait] 

which can use (and works):

scala> tag("lala") res7: @@[string,mytrait] = lala 

my question is: how? how doesn't throw classcastexception: s.asinstanceof[string @@ mytrait]. point of view, "lala" of type string not of type string { type tag = mytrait} since instantiated usual string object. magic asinstanceof method?

first, note whole point of tagged types avoid runtime overhead, means can't expect runtime type checks work distinguishing them!

asinstanceof runtime cast, , jvm doesn't know scala type system (or java's); has classes, interfaces, , primitives. asinstanceof can cast erased type, i.e. closest jvm equivalent of scala type. erased type of string { type tag = mytrait} string, succeeds.

the relevant parts of specification are:

  1. standard library defines asinstanceof follows:

    /** type cast; needs inlined work given */ def asinstanceof[a]: = match {   case x: => x   case _ => if (this eq null)             else throw new classcastexception() } 
  2. type patterns explains how x: string { type tag = mytrait } matched:

    types not of 1 of forms described above accepted type patterns. however, such type patterns translated erasure. scala compiler issue "unchecked" warning these patterns flag possible loss of type-safety.

  3. finally,

    the erasure of compound type t1 … tn {r} erasure of intersection dominator of t1,…,tn.

    in case t1 string, t2 anyref { type tag = mytrait }, intersection dominator of string , anyref, string.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -