首页 > 解决方案 > 访问数组内的数组

问题描述

我是 scala 编码的新手,我对某些东西很好奇,很难在网上找到答案。我有这个数组,它接受多个不同类型的参数(:Any)

val arguments= Array("Monday",10,20,Array("test","test2"), if(4 == 4){ "true"})

我迭代并打印了其中的内容。除了索引 3 处的数组之外,所有内容都正确打印。我得到了我相信的对象内存地址,这是可以理解的——Java 也会发生同样的事情。但我很好奇,你将如何访问它?

我尝试将 arguments(3) 的值保存在数组中(val arr:Array[String] = arguments(3)),但由于类型不匹配,它不起作用(any != Array[String])

有小费吗?这可能是我对函数式编程理解的一个差距。

标签: arraysscalaany

解决方案


您正在迭代的是Array[Any],因此您可以执行Any类型可用的功能。您可以使用模式匹配访问数组中的项目,它使用底层的unapply方法来查看它是否可以将您Any变成更具体的东西:

  val arguments= Array("Monday",10,20,Array("test","test2"), if(4 == 4){ "true"})

  arguments foreach { arg =>
    arg match {
      case a:Array[String] => println(s"This is the array: ${a.mkString(",")}, and I can do array functions ${a.contains("test")}")
      case _ => println(s"Otherwise I have this: $arg")
    }
  }
//  stdout:
//  Otherwise I have this: Monday
//  Otherwise I have this: 10
//  Otherwise I have this: 20
//  This is the array: test,test2, and I can do array functions true
//  Otherwise I have this: true


推荐阅读