Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scala function – Type mismatch. Required: Null. Found: String

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading