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 case
return are Array[Int]
, the res
type is Array[Int]
.
- The above code changes, a
case
returnArray[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 res
type of either Array[Int]
or Array[String]
.
This shows that the compiler will try to use smaller types to include all case
.
- 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 case
types 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
.
How Array
content 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.
The solution is as follows:
- Use for loop to output
for(item <- res){
println(item)
}
To ensure that res
is Array
the 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 a
the contents of the object, first of all need to asInstanceOf
be converted.