Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take first three letters in the string

Tags:

list

scala

I need to retrieve first three letters

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

if(t){
  Test("found")
 }else{
   None
 }

Is there a efficient way to code for the above logic

like image 831
coder25 Avatar asked Dec 22 '25 14:12

coder25


1 Answers

"abc".take(2) match {
  case "ab" => Test("found")
  case _ => None
}

for String, you can use take to get chars like Seq, and it's more safe than substring to avoid StringIndexOutOfBoundsException exception.

and since you are returning None when not match, Test("found") Shouldn't be Some(Test("found"))?

like image 163
chengpohi Avatar answered Dec 24 '25 04:12

chengpohi