How come I cannot assign variables in Scala in the following manner?
开发者_运维知识库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:
error: type mismatch;
found : Date
required: Null
startDateTime = date; // error
This says, it thinks startDateTime
should be of type Null, but you are giving it a Date
.
The fix is to explicitly type startDateTime
as follows:
var startDateTime : Date = /* some sort of default date */
If your startDateTime
is truly optional, consider using Scala's Option instead of using null
. This would make your function look like this:
def getVWAP(date: Date, maxEvents: Int): Double = {
var startDateTime: Option[Date] = None;
if (maxEvents > 0) {
startDateTime = Some(date);
}
0.0
}
You can read more about the philosophy of Option
versus null
here. Overly summarized, null
is about run-time checking, resulting in a NullPointerException
if some variable is null, and Option
is about compile-time checking, resulting in a compiler error indicating a potential non-value must be handled. Using Option
says you'd rather know at compile time.
Because startDateTime
is declared with type Null
. Can't assign a date to that. Declare a type for startDateTime
in your declaration.
It's probably because they type of startDateTime
is not inferred as a Date
. Try replacing that line with
var startDateTime:Date = //(some initialized Date value)
One big difference between Scala and Java that you'll find is the avoidance of using null
. If you really want a variable that might not be set, you should look into Options
In that case, you would define your startDateTime as
var startDateTime:Option[Date] = None
if(maxEvents > 0){
startDateTime = Some(date)
}
精彩评论