1

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

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
igx
  • 4,101
  • 11
  • 43
  • 88
  • 1
    Try this snippet instead: `val x: Long = OptionLong.fold(ifEmpty = 1L)(Long.unbox)` - What that flag does is create a warning everytime an implicit conversion is applied to an **Option** operation _(like `getOrElse`)_ in this case, the problem is that since your option is of type **java.lang.Long**, then it has to cast the `1L`_(which is of type **scala.Long**)_ to it first, and then after the `getOrElse` it has to cast it to **scala.Long** again. – Luis Miguel Mejía Suárez Aug 12 '19 at 13:20
  • @LuisMiguelMejíaSuárez Probably you meant `Option[Long](timestamp()).fold(ifEmpty = 1L)(Long.unbox)`. – Dmytro Mitin Aug 12 '19 at 13:29
  • @DmytroMitin oh the code was different when I made the comment, since I was _(am)_ on the cellphone, I couldn't check how to reproduce the error and if my code fixed it, but I guess it should work given `OptionLong` was defined with a type of **Option[java.lang.Long]** and the expected default was `1L`. – Luis Miguel Mejía Suárez Aug 12 '19 at 15:15
  • @LuisMiguelMejíaSuárez Well, I can't reproduce OP's error, but I'm afraid `Option[Long](timestamp())` is calculated before `.fold` is called, so I guess linter may emit warning anyway. – Dmytro Mitin Aug 12 '19 at 15:19

2 Answers2

1

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)
0

Probably you also have -Xfatal-warnings switched on.

Try to use https://github.com/ghik/silencer

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

Actually I can't reproduce. What is the definition of timestamp()? With public static long timestamp() { return System.currentTimeMillis(); } I can't reproduce.

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66