I am getting an below error while executing program....Does anyone help me with that which change I need to do it with recursion as I am new in scala?
type mismatch;
found : Any
required: Array[Any]
array11(arr(acc),0)
Below is my code
object arr11 {
def main(args: Array[String]): Unit = {
array11(Array(Array(1, 2, 11),0),0)
}
def array11(arr:Array[Any],acc:Int):Unit = {
if(arr(acc).isInstanceOf[Array[Any]])
{
array11(arr(acc),0)
}
}
CodePudding user response:
take a look at function array11
:
def array11(arr: Array[Any], acc: Int):Unit = {
if(arr(acc).isInstanceOf[Array[Any]]) {
array11(arr(acc),0)
}
}
array11
takes two arguments, first - arr
should have type Array[Any]
, but in line:
array11(arr(acc), 0)
arr(acc)
will have type Any
(because arr is Array
of Any
) and you are trying to pass an object of Any
type as Array[Any]
and the compiler shows you the error: type mismatch
.
To make your code correct for compiler you should make cast arr(acc)
to Array[Any]
type, for example using asInstanceOf
:
def array11(arr: Array[Any], acc: Int): Unit = {
if(arr(acc).isInstanceOf[Array[Any]]) {
array11(arr(acc).asInstanceOf[Array[Any]], 0)
}
}
But your code has a very low type-safety in this case, you should get rid of using Any
type in signatures as possible. Also using asInstanceOf
- is a bad practice for the same reasons. I would advise you to refactor your array11
function to make it more type-safe.
CodePudding user response:
Even if you do if (x.isInstaceOf[X])
, the compiler still does not assume the type of x
to be X
, it is still the same as it was before the if
. This is different in some languages, like Kotlin. In Scala if you want to do a thing like this, you use the pattern matching:
def array11(arr:Array[Any],acc:Int):Unit = {
arr(acc) match {
case aa: Array[Any] =>
array11(aa,0)
case _ =>
}
}