None incompatible type with Option

Compiling function below produces a weird error,

def sqrtOption(n:Int):(Option[Double])=
    var ret:Option[Double]=Some(0.0)
    if n>=0 then
      ret=Some(Math.sqrt(n))
    else
      ret=None
    end if
    ret
  end sqrtOption

Error:

../compile 
-- [E007] Type Mismatch Error: Test.scala:21:10 ----------------------------------------------------------------
21 |      ret=None
   |          ^^^^
   |          Found:         |None.type
   |          Required:      |Option[Double]

Explanation
===========

Tree:    21|None

I tried to show that
       |None.type
conforms to
       |Option[Double]
but the comparison trace ended with `false`:

Uhm, I would venture and say the problem is due strict equality.

Anyways, you don’t need the parenthesis around the return type; that may also be causing problems.
And, there is no need for mutability, remember that in Scala an if is an expression not a statement.

def sqrtOption(n:Int): Option[Double] =
  if n>=0 then
    Some(Math.sqrt(n))
  else
    None
  end if
end sqrtOption

Can’t reproduce the issue with Scala 3.1.3 in IntelliJ or sbt (1.5.5).

Maybe it’s some bug in scala 3.1.0
This my ugly workaround:

def sqrtOption(n:Int):Option[Double]=
    if n>=0 then
      Some(Math.sqrt(n))
    else
      Option.empty[Double]
    end if
  end sqrtOption

  def sqrtOrZero(n:Int):Double=
    if sqrtOption(n).isEmpty then
      0.0
    else
      sqrtOption(n) match
        case Some(result) => result
        case _ => 0.0
    end if
  end sqrtOrZero

  println(sqrtOrZero(-4))

I wouldn’t say ugly, Option.empty is very useful and common to improve type inference.
Also, again, this seems to be related to strict equality, can you confirm if you have that enabled?

Finally, your code can be simplified like this:

def sqrtOption(n: Int): Option[Double] =
  if n>=0 then
    Some(Math.sqrt(n))
  else
    Option.empty
  end if
end sqrtOption

def sqrtOrZero(n: Int): Double =
  sqrtOption(n).getOrElse(default = 0.0D)
1 Like

This is the compile command i use

scalac Test.scala -Werror -deprecation -feature -unchecked -indent -new-syntax -print-lines -explain -explain-types

I can’t reproduce the problem using those flags and coursier to launch that version of the compiler.