从 Option(lang.Long) 转换为 Long 时隐式视图的可疑应用

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

将此标志添加到 scalacoptions 后:

  "-Xlint:option-implicit"

我不明白为什么会出现这个问题以及如何解决它

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)

代码如下所示

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

函数时间戳可以为 null 或 return java Long

可能您还开启了 -Xfatal-warnings

尝试使用https://github.com/ghik/silencer

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

其实我无法重现。 timestamp()的定义是什么?使用 public static long timestamp() { return System.currentTimeMillis(); } 我无法重现。

我能够使用以下代码复制消息:

$ 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.

现在,您可以通过以下方式修复它。

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)