简体   繁体   中英

Scala: Check for null for List

I am new to Scala after coding for 10 years in Java. Still getting hold of functional programming. How can I check if the list is null or not? Code looks something like this:

val filterList = filters.map { filter =>
        //some operations
      }

//Other function

filterList.foldLeft(true)((result1, result2) => {

Now if filters is null then filterList is going to be null too.

If filters is null (which is different from being empty) then that indicates some pretty careless programing, but it can be handled.

val filterList = Option(filters).map(_.map { ...

Now filterList is of type Option[X] where X is the collection type for filters . Note the 1st map is to unwrap the Option and the 2nd map maps over the collection, except if filters was null , then the 2nd map is never invoked and the whole result is None .

val filterList = if(filters == null) Seq.empty[SomeType] else filters.map {...}

However, you should try to make sure it never gets to be null, because we try to avoid null variables in Scala. Use the Option[T] type, or empty collections instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM