I have stripped down the method so it doesn’t make logical sense but I am just trying to resolve the compile error
def getVWAP(date: Date, maxEvents: Int): Double = {
var startDateTime = null;
if (maxEvents > 0) {
startDateTime = date; // error
}
0.0
}
Scala has used type inference to deduce the type of the variable
startDateTime, which you did not specify a type for. So, Scala emits the following error:This says, it thinks
startDateTimeshould be of type Null, but you are giving it aDate.The fix is to explicitly type
startDateTimeas follows:If your
startDateTimeis truly optional, consider using Scala’s Option instead of usingnull. This would make your function look like this:You can read more about the philosophy of
Optionversusnullhere. Overly summarized,nullis about run-time checking, resulting in aNullPointerExceptionif some variable is null, andOptionis about compile-time checking, resulting in a compiler error indicating a potential non-value must be handled. UsingOptionsays you’d rather know at compile time.