语义startsWith的阵列 [英] Semantic of startsWith on Arrays

查看:193
本文介绍了语义startsWith的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被这前pression猝不及防:

I was caught off guard by this expression:

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

这建筑是错误的,因为顺序[数组[字符串]] 而不是intented 序列[字符串]
我没想到的是阵列将有一个 startsWith 的方法,所以我打了一下它,了解它的语义。我自然希望这是真的:阵列(你好,世界)startsWith(你好)

This construction is faulty, as words is a Seq[Array[String]] instead of the intented Seq[String]. I didn’t expect that Array would have a startsWith method, so I played a bit with it to understand its semantics. I naturally expected this to be true: Array("hello", "world").startsWith("hello")

下面是我探索会话的其​​余部分:

Here’s the rest of my exploration session:

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预期的行为?

What is the expected behavior of ‘array.startsWith’ ?

推荐答案

以下文档:

DEF startsWith [B](即:GenSeq [B]):Boolean测试这是否可变
  索引序列开始与给定的序列

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

所以 array.startsWith(X)期望 X 是一个序列。

So array.startsWith(x) expects x to be a sequence.

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

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

What happens in the question above is that the string passed as parameter is evaluated as a sequence of characters. That leads to no compiler error although in that specific case it will not yield the expected result.

这应该说明:

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

这篇关于语义startsWith的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆