Check if a string is blank or doesn't exist in Scala

前端 未结 9 1172
误落风尘
误落风尘 2021-02-01 16:29

I have an Option[String].

I want to check if there is a string exists and if it\'s exists its not blank.

def isBlank( input : Option[Strin         


        
9条回答
  •  庸人自扰
    2021-02-01 17:04

    I am from C# background and found Scala implicit methods similar to C# extensions

    import com.foo.bar.utils.MyExtensions._
    ...
    
    "my string".isNullOrEmpty  // false
    "".isNullOrEmpty           // true
    " ".isNullOrEmpty          // true
    "  ".isNullOrEmpty         // true
    
    val str: String  = null
    str.isNullOrEmpty          // true
    

    Implementation

    package com.foo.bar.utils
    
    object MyExtensions {
    
      class StringEx(val input: String) extends AnyVal {
    
        def isNullOrEmpty: Boolean =    
          if (input == null || input.trim.isEmpty)
            true
          else
            false
      }
    
      implicit def isNullOrEmpty(input: String): StringEx = new StringEx(input)
    }
    

提交回复
热议问题