1

I have Scala class that will generate an Option[StructType] value which will be used in a Java function. In that java function, I need to check if this Option[StructType] is Scala None or not. How do I do that?

Scala class:

class Person(columns : String) {
    val recordStruct : Option[StructType] = {
        if ( columns != null && !columns.isEmpty()) {
          Some(new StructType(fields.map(field => 
                              StructField(field, StringType, true)).toArray))
        } else {
            None
        }
    }   
}

Java function:

StructType structure =  person.recordStruct().get();

// how to check if structure is None (in scala) ????

if (structure is None) {
    // ...
}
6
  • if(!structure.isDefined()) would tell you if structure is None. Except that structure isn't really an Option. person.recordStruct() is. Commented Mar 26, 2016 at 20:55
  • I don't see structType has a isDefined() function. Commented Mar 26, 2016 at 20:57
  • that's because structType isn't an Option (it's a StructType, duh). See my updated comment above. Commented Mar 26, 2016 at 20:58
  • You can just do StructType structure = person.recordStruct().orNull() if you prefer Commented Mar 26, 2016 at 21:02
  • so I should use person.recordStruct().isDefined(), not structure.isDefined() ? Commented Mar 26, 2016 at 21:02

1 Answer 1

6
Option<StructType> maybeStructure = person.recordStruct();
if (maybeStructure.isEmpty()) { 
    // do something if None
} else {
    StructType structure =  person.recordStruct().get();
    // now you can use structure...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. By looking at them, it seems I can use either isDefined() or isEmpty() on Option type.
Correct - of course o.isDefined() == !o.isEmpty().

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.