How to check if a string is blank (empty, none, or contains only whitespace) in Scala

1 Answer

0 votes
object IsBlankOrEmpty {
  def isBlankOrEmpty(str: Option[String]): Boolean = {
    // Check for None or empty string
    str match {
      case Some(s) if s.nonEmpty => s.forall(_.isWhitespace)
      case _ => true
    }
  }

  def main(args: Array[String]): Unit = {
    val testCases = List(None, Some(""), Some("   "), Some("abc"))

    testCases.zipWithIndex.foreach { case (test, index) =>
      println(s"Test${index + 1}: ${isBlankOrEmpty(test)}")
    }
  }
}



 
/*
run:

Test1: true
Test2: true
Test3: true
Test4: false

*/

 



answered Jun 8, 2025 by avibootz
...