【问题标题】:How to distinguish parameteric types?如何区分参数类型?
【发布时间】:2020-09-24 00:49:09
【问题描述】:

我对 Scala 中的子类型感到困惑。我的主要问题是如何区分C[T1]C[T2]。有两种情况:

  1. C[T1] "等于" C[T2] 因为它们都是C 的子类型。
  2. 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[]

我现在想知道有什么方法可以做到这一点吗?

【问题讨论】:

标签: scala generics reflection scala-reflect erasure


【解决方案1】:

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(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

Type Erasure in Scala

C[T1] "equals" C[T2] 因为它们都是C 的子类型。

它们不是子类型

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

Subtype in Scala: what is "type X <: Y"?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2012-12-22
    • 1970-01-01
    相关资源
    最近更新 更多