Search code examples
scalaimplicit-conversionscalaclinter

getting Suspicious application of an implicit view when converting from Option(lang.Long) to Long


after adding this flag to scalacoptions :

  "-Xlint:option-implicit"

I don't understand why am I getting this and how to resolve it

Error:(47, 34) Suspicious application of an implicit view (scala.Predef.Long2long) in the argument to Option.apply. val x: Long = Option[Long](timestamp()).getOrElse(1L)

The code looks like this

val x: Long = Option[Long](timestamp()).getOrElse(1L)

the function timestamp can be null or return java Long


Solution

  • I was able to replicate the message with the following code:

    $ scala -Xlint:option-implicit
    Welcome to Scala 2.13.0 (OpenJDK 64-Bit Server VM, Java 1.8.0_222).
    Type in expressions for evaluation. Or try :help.
    
    scala> def timestamp(): java.lang.Long = new java.lang.Long("10")
    
    scala> val x: Long = Option[Long](timestamp()).getOrElse(1L)
    warning: Suspicious application of an implicit view (scala.Predef.Long2long) in the argument to Option.apply.
    

    Now, you can fix it the following way.

    val x: Long = Option(Long.unbox(timestamp())).getOrElse(1L)
    
    // Or, supposing opt is of type Option[java.lang.Long]
    val x: Long = opt.fold(ifEmpty = 1L)(Long.unbox)