如何解决如何区分参数类型?
我对Scala中的亚型感到困惑。我的主要问题是如何区分C[T1]
和C[T2]
。有两种情况:
-
C[T1]
之所以等于C[T2]
,因为它们都是C
的子类型。 -
C[T1]
不等于C[T2]
,因为C[T1]
和C[T2]
最终是不同的类型。
我尝试了类似.getClass
的方法,但由于我们具有原始类型,因此该策略似乎行不通。
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[]
我现在想知道有什么方法可以做到这一点吗?
解决方法
List[Int]
和List[Double]
具有相同的类别,但具有不同的类型。
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]
和Array[Double]
的类和类型都不同。
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())))
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
C[T1]
之所以等于C[T2]
,因为它们都是C
的子类型。
它们不是子类型。
https://www.scala-lang.org/files/archive/spec/2.13/03-types.html#conformance
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。