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
"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"))?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With