arrays - 访问数组内的数组
问题描述
我是 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])
有小费吗?这可能是我对函数式编程理解的一个差距。
解决方案
您正在迭代的是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
推荐阅读
- apache-flink - 如何连接一个流和两个静态配置单元表
- reactjs - 从 json 文件一次显示 1 个值
- java - 我应该如何将 json 值返回到另一个方法中
- javascript - Web 客户端无法连接到 MQTT Web 套接字
- file - sh - 根据最大值将 0 附加到文件名
- git - Unity 2019 中软件包的版本控制
- nlp - 如何从词嵌入中恢复某个词出现在给定上下文中的可能性?
- javascript - .map() 参数未定义
- opencv - OpenCV dnn、OpenCL 和 Nvidia 显卡
- php - 对表上的 PHP/SQL 删除没有影响