Arrays 基于数组的startsWith语义
这句话让我措手不及:Arrays 基于数组的startsWith语义,arrays,scala,collections,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]。 我没想到这个数组会有一个startsWith方法,所以我用它来理解它的语义。我自然希望这是真的:Array
val words = strings.map(s => s.split(“,”)) // split CSV data
val nonHashWords = words.filter(word => word.startsWith(“#”))
这种结构是错误的,因为words
是一个Seq[Array[String]]
而不是预期的Seq[String]
。
我没想到这个数组会有一个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]):布尔测试此变量是否可变
索引序列从给定序列开始
所以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