Come distinguere i tipi parametrici?
Sono confuso sui sottotipi in Scala. La mia domanda principale è come distinguere C[T1]da C[T2]. Esistono due scenari:
C[T1]"uguale"C[T2]perché sono tutti sottotipi diC.C[T1]non "uguale"C[T2]perchéC[T1]eC[T2]alla fine sono tipi diversi.
Ho provato alcuni modi come .getClass, sembra che questa strategia non funzionerà perché abbiamo tipi primitivi.
println(List[Int](1).getClass == List[Double](1.0).getClass) // True
println(List[Int](1).getClass.getCanonicalName) // scala.collection.immutable.$colon$colon
println(Array[Int](1).getClass == Array[Double](1.0).getClass) // False
println(Array[Int](1).getClass.getCanonicalName) // int[]
Ora mi chiedo se ci sia un modo per farlo?
Risposte
List[Int]e List[Double]hanno la stessa classe , ma tipi diversi .
import scala.reflect.runtime.universe._
println(typeOf[List[Int]] =:= typeOf[List[Double]])//false
println(typeOf[List[Int]].typeConstructor =:= typeOf[List[Double]].typeConstructor)//true
println(typeOf[List[Int]])//List[Int]
println(showRaw(typeOf[List[Int]]))//TypeRef(SingleType(SingleType(ThisType(<root>), scala), scala.package), TypeName("List"), List(TypeRef(ThisType(scala), scala.Int, List())))
println(classOf[List[Int]] == classOf[List[Double]])//true
println(classOf[List[Int]])//class scala.collection.immutable.List
println(classOf[List[Int]].getCanonicalName)//scala.collection.immutable.List
Array[Int]e Array[Double]hanno classi e tipi diversi.
println(typeOf[Array[Int]] =:= typeOf[Array[Double]])//false
println(typeOf[Array[Int]].typeConstructor =:= typeOf[Array[Double]].typeConstructor)//true
println(typeOf[Array[Int]])//Array[Int]
println(showRaw(typeOf[Array[Int]]))//TypeRef(ThisType(scala), scala.Array, List(TypeRef(ThisType(scala), scala.Int, List())))
println(classOf[Array[Int]] == classOf[Array[Double]])//false
println(classOf[Array[Int]])//class [I
println(classOf[Array[Int]].getCanonicalName)//int[]
https://docs.scala-lang.org/overviews/reflection/overview.html
https://typelevel.org/blog/2017/02/13/more-types-than-classes.html
Digita Erasure in Scala
C[T1]"uguale"C[T2]perché sono tutti sottotipi diC.
Non sono sottotipi .
https://www.scala-lang.org/files/archive/spec/2.13/03-types.html#conformance
Sottotipo in Scala: cos'è il "tipo X <: Y"?