Black monkey house: Scala type of pattern matching

Any type of object can be matched, but not directly match a generic type, this abstract description, see the following example: significance of doing so is to avoid the use of isInstanceOf asInstanceOf and methods.

After the introduction of the generic concept of the JDK 1.5 //
// generic erased
// preparation time
// List <String> list = new ArrayList <String> ()
to run the compiler //
// List List = new new ArrayList ()
/ / With generics time of writing, erasing the generic runtime, for backwards compatibility
// java erased it is generic, not a generic array, not erased. Say so strict, in an array scala also generics, generics scala erase, wipe the jvm is generic, that is java generics

Compile former
Case the Map [String, Integer]
Case the Map [Integer, String]
compiled
Case the Map
Case the Map
compiled, are erased, why write type it? Standardization of development, erase, for backwards compatibility

println("匹配之类型模式 不能精准匹配泛型类型----------------")
val a = 2

val obj = if (a == 1) 1
else if (a == 2) "2"
else if (a == 3) BigInt(3)
else if (a == 4) Map("aa" -> 1)
else if (a == 5) Map(1 -> "aa")
else if (a == 6) Array(1, 2, 3)
else if (a == 7) Array("aa", 1)
else if (a == 8) Array("aa")

val r1 = obj match {
  case x: Int => x
  case s: String => "这是2字符串"
  case bi: BigInt => "BigInt 类型的"
  case _: BigInt => "BigInt类型 "
  case m: Map[String, Integer] => "Map[String, Int]类型的Map集合"
  case m: Map[Integer,String] => "Map[int,String]类型的Map集合"
  case m: Map[_, _] => "Map[_,_]集合"
  case a: Array[Int] => "It's an Array[Int]"
  case a: Array[String] => "It's an Array[String]"
  case a: Array[_] => "It's an array of something other than Int Arrya[_]"
  case _ => 0
}

println(r1 + ", " + r1.getClass.getName)

尖叫提示:Map类型的泛型在匹配的时候,会自动删除泛型类型,只会匹配到Map类型,而不会精确到Map里面的泛型类型。

//java擦除的是泛型,数组不是泛型,不擦除。 这么说不严谨,在scala中数组也是泛型, scala中泛型擦除,擦的是jvm泛型,也就是java泛型

Scala 中数组也是泛型,但是Scala 中的数组编译后,就不是泛型,Scala 中的数组是可以精确匹配类型的

Reproduced in: https: //www.jianshu.com/p/0b2727073b7c

Guess you like

Origin blog.csdn.net/weixin_33720078/article/details/91182452