Scala 取字符串中的前三个字母

Scala 取字符串中的前三个字母,scala,list,Scala,List,我需要找回前三封信 val s ="abc" val t = s.substring(0,2).equals("ab") case class Test(id :String) if(t){ Test("found") }else{ None } 是否有一种有效的方法为上述逻辑编码 "abc".take(2) match { case "ab" => Test("found") case _ => None } 对于String,您可以使用take获取像S

我需要找回前三封信

val s ="abc"
val t = s.substring(0,2).equals("ab")
case class Test(id :String)

if(t){
  Test("found")
 }else{
   None
 }
是否有一种有效的方法为上述逻辑编码

"abc".take(2) match {
  case "ab" => Test("found")
  case _ => None
}
对于
String
,您可以使用
take
获取像
Seq
这样的字符,并且它比
substring
更安全,以避免
StringIndexOutOfBoundsException
异常

由于不匹配时返回的是
None
Test(“found”)
不应该是
Some(Test(“found”)

一行:

case class Test(id: String)
val s = "abc"

if (s.take(2) == "ab") Test("found") else None

确保字符串长度至少为2个字符,否则
take
将引发异常。

take
不会引发异常。它只返回要返回的内容:
math.min(math.max(直到,0),length)
(即scala 2.12.8)