如何检查Java代码中的scala Option类型是否为None

时间:2016-03-26 20:52:39

标签: java scala

我有Scala类,它将生成一个Option[StructType]值,该值将用于Java函数。在那个java函数中,我需要检查这个Option[StructType]是否是Scala None。我该怎么做?

Scala类:

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函数:

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

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

if (structure is None) {
    // ...
}

1 个答案:

答案 0 :(得分:5)

Option<StructType> maybeStructure = person.recordStruct();
if (maybeStructure.isEmpty()) { 
    // do something if None
} else {
    StructType structure =  person.recordStruct().get();
    // now you can use structure...
}