Como distinguir os tipos de parâmetros?
Estou confuso sobre os subtipos no Scala. Minha principal questão é como distinguir C[T1]de C[T2]. Existem dois cenários:
C[T1]"iguais"C[T2]porque são todos subtipos deC.C[T1]não é "igual"C[T2]porqueC[T1]eC[T2]são de tipos diferentes eventualmente.
Eu tentei algumas maneiras como .getClassparece que essa estratégia não funciona porque temos tipos primitivos.
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[]
Agora me pergunto: há alguma maneira de fazer isso?
Respostas
List[Int]e List[Double]têm a mesma classe , mas tipos diferentes .
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]têm diferentes classes e tipos.
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
Apagar tipo em Scala
C[T1]"iguais"C[T2]porque são todos subtipos deC.
Eles não são subtipos .
https://www.scala-lang.org/files/archive/spec/2.13/03-types.html#conformance
Subtipo em Scala: o que é "tipo X <: Y"?