1

Scala newbie here...

Doing below on address java object with getStLine*() methods... yields a List with empty strings for the empty strings returned. whats the Scala way to cleanly not add empty strings to a list.

val streets = List[String](addr.getStLine1, addr.getStLine2, addr.getStLine3)

1 Answer 1

5

Looks like you're explicitely adding strings to list, I don't think you'd be able to easily avoid adding empty strings without custom derived list implementation. On the other hand you can easily filter out empty strings after the fact.

scala> val z = List("one", "", "three")
z: List[java.lang.String] = List(one, "", three)

scala> z.filter(p=> p!=null && !p.equals(""))
res2: List[java.lang.String] = List(one, three)
Sign up to request clarification or add additional context in comments.

6 Comments

Yes, I do like the looks of this: streets.filterNot(s => s == null || s == "" )
More idomatic : z.filter(!_.isEmpty)
@n1r3 that'll throw null pointer, isEmpty checks for 0 length, not nulls
the question is "cleanly not add empty strings", I didn't see anything about null in the question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.