arrays - 数组的startsWith 语义

标签 arrays scala collections

这句话让我措手不及:

val words = strings.map(s => s.split(“,”)) // split CSV data
val nonHashWords = words.filter(word => word.startsWith(“#”))

此构造是错误的,因为 words 是一个 Seq[Array[String]],而不是预期的 Seq[String]。 我没想到 Array 会有一个 startsWith 方法,所以我稍微研究了一下它来理解它的语义。我自然希望这是真的:Array(“hello”, “world”).startsWith(“hello”)

这是我探索过程的其余部分:

scala> val s = Array("hello","world")
s: Array[String] = Array(hello, world)

scala> s.startsWith("hello")
res0: Boolean = false

scala> s.startsWith("h")
res1: Boolean = false

scala> val s = Array("hello","hworld")
s: Array[String] = Array(hello, hworld)

scala> s.startsWith("h")
res3: Boolean = false

scala> s.startsWith("hworld")
res4: Boolean = false

scala> s.toString
res5: String = [Ljava.lang.String;@11ed068

scala> s.startsWith("[L")
res6: Boolean = false

scala> s.startsWith("[")
res7: Boolean = false

“array.startsWith”的预期行为是什么?

最佳答案

按照文档:

def startsWith[B](that: GenSeq[B]): Boolean Tests whether this mutable indexed sequence starts with the given sequence.

因此 array.startsWith(x) 期望 x 是一个序列。

scala> val s = Array("hello","world")
scala> s.startsWith(Seq("hello"))
res8: Boolean = true

上面问题中发生的情况是,作为参数传递的字符串被评估为字符序列。这不会导致编译器错误,尽管在特定情况下它不会产生预期的结果。

这应该说明:

scala> val hello = Array('h','e','l','l','o',' ','w','o','r','l','d')
hello: Array[Char] = Array(h, e, l, l, o,  , w, o, r, l, d)

scala> hello.startsWith("hello")
res9: Boolean = true

关于arrays - 数组的startsWith 语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37192390/

相关文章:

java - IntelliJ - 无法解析符号 'Arrays'

c - 请告诉我这段 C 中二维动态数组代码中的错误

javascript - 我正在尝试将 "grades"添加到数组,但它没有按计划进行

c++ - 在 C++ 中使用合并函数算法时遇到问题

scala - Spark DataFrame 列名称未传递给从属节点?

scala - 如何从 org.apache.spark.mllib.linalg.SparseVector 转换为 org.apache.spark.ml.linalg.SparseVector?

scala - 尽管使用了 import sqlContext.implicits._,但 toDF 无法编译

arrays - Clickhouse:计算两个日期之间的差异,不包括某些天(但不包括周末!)

Java -> Scala,集合性能

java - 从 HashMap 中检索记录