¿Cómo distinguir tipos de parámetros?

Sep 22 2020

Estoy confundido acerca de los subtipos en Scala. Mi pregunta principal es cómo distinguir C[T1]entre C[T2]. Hay dos escenarios:

  1. C[T1]"es igual" C[T2]porque todos son subtipos de C.
  2. C[T1]no "igual" C[T2]porque C[T1]y C[T2]eventualmente son tipos diferentes.

He probado algunas formas como .getClass, parece que esta estrategia no funcionará porque tenemos 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[]

Ahora me pregunto, ¿hay alguna forma de que pueda hacer esto?

Respuestas

4 DmytroMitin Sep 22 2020 at 18:05

List[Int]y List[Double]tienen la misma clase , pero de diferentes tipos .

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]y Array[Double]tienen diferentes clases y 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

Borrado de tipo en Scala

C[T1]"es igual" C[T2]porque todos son subtipos de C.

No son subtipos .

https://www.scala-lang.org/files/archive/spec/2.13/03-types.html#conformance

Subtipo en Scala: ¿qué es "tipo X <: Y"?