这句话让我措手不及:
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/