Discussion on Return Type of Scala Pattern Matching

val arr = Array(1,2)

val res = arr match {
    case Array(x,y) => Array(y,x)
    case Array(x,y,z) => Array(0)
    case _ => Array(-1)
}

For the above code, because all the casereturn are Array[Int], the restype is Array[Int].
Insert picture description here

  1. The above code changes, a casereturnArray[String]
val arr = Array(1,2)

 val res = arr match {
     case Array(x,y) => Array(y,x)
     case Array(x,y,z) => Array("1")
     case _ => Array(-1)
 }

The restype of either Array[Int]or Array[String].
Insert picture description here
This shows that the compiler will try to use smaller types to include all case.

  1. Modify again, let's take a look
val arr = Array(1,2)

val res = arr match {
     case Array(x,y) => Array(y,x)
     case Array(x,y,z) => Array("1")
     case _ => println(" ")
 }

The three casetypes of returns are not the same, where the default branch returns Unit, so you want to include the three types of the type should be Any.

Insert picture description here

How Arraycontent output:

If direct Println(arr)is unable to get content, but returns the object signature (if this is the terminology I'm not sure), which is the underlying reason I do not know.
Insert picture description here
The solution is as follows:

  • Use for loop to output
for(item <- res){
    
    
    println(item)
}

To ensure that resis Arraythe type otherwise required by res.asInstanceOf[Array[int]]downlink conversion.

  • Conversion is called other object output, such as List
println(res.toList)

If the static type of the object is Any, the dynamic type is Array. That is, the parent class is used to refer to the subclass object, namelyAny a = Array[Int]

So you want to output athe contents of the object, first of all need to asInstanceOfbe converted.

Guess you like

Origin blog.csdn.net/weixin_39139505/article/details/107568528