I have a problem with type mismatch in Scala Function. Compiler returns an error:
def isLarger(inputNum: Int) = {
var res = null
if (inputNum.>(10)) {
res = "aaa"
}
res
}
If inputNum larger than 10, return String "aaa" if not, return null.
But Type match.
Why? Any idea what could be the problem?
>Solution :
Try to add type declaration
var res: String = null
By the way, you don’t need a var. If-else is an expression
def isLarger(inputNum: Int) = {
val res: String =
if (inputNum > 10)
"aaa"
else null
res
}
The concept of absent value is better expressed with Option rather than null
def isLarger(inputNum: Int) =
if (inputNum > 10)
Some("aaa")
else None