加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 隐式转换和null

发布时间:2020-12-16 08:56:41 所属栏目:安全 来源:网络整理
导读:以下代码 import scala.language.implicitConversionsobject myObj { implicit def nullToInt(x: Null) = 0 def main(args: Array[String]): Unit = { val x = 1 + null val y = 1 + nullToInt(null) println(x + " " + y) }} 给出以下结果 1null 1 我期待两
以下代码

import scala.language.implicitConversions

object myObj {
  implicit def nullToInt(x: Null) = 0

  def main(args: Array[String]): Unit = {
    val x = 1 + null
    val y = 1 + nullToInt(null)

    println(x + " " + y)
  }
}

给出以下结果

1null 1

我期待两个val都是Int并且等于1.

显然,第一个val是String,等于“1null”.

Xprint:typer显示源代码被翻译成

package <empty> {
  import scala.language.implicitConversions;
  object myObj extends scala.AnyRef {
    def <init>(): myObj.type = {
      myObj.super.<init>();
      ()
    };
    implicit def nullToInt(x: Null): Int = 0;
    def main(args: Array[String]): Unit = {
      val x: String = 1.+(null);
      val y: Int = 1.+(myObj.this.nullToInt(null));
      scala.Predef.println(x.+(" ").+(y))
    }
  }
}

int没有符号方法接受null

scala> 10+null
res0: String = 10null

scala> 10*null
<console>:12: error: overloaded method value * with alternatives:
  (x: Double)Double <and>
  (x: Float)Float <and>
  (x: Long)Long <and>
  (x: Int)Int <and>
  (x: Char)Int <and>
  (x: Short)Int <and>
  (x: Byte)Int
 cannot be applied to (Null)
       10*null
         ^

scala> 10-null
<console>:12: error: overloaded method value - with alternatives:
  (x: Double)Double <and>
  (x: Float)Float <and>
  (x: Long)Long <and>
  (x: Int)Int <and>
  (x: Char)Int <and>
  (x: Short)Int <and>
  (x: Byte)Int
 cannot be applied to (Null)
       10-null
         ^

我假设“1”和“null”都转换为String而不是应用隐式nullToInt.有人可以解释编译器如何提出这个问题吗?使用了什么逻辑/工作流程?

另一个问题是是否有办法启用implcit nullToInt?

PS.我不是在谈论这里的最佳做法.随意考虑一个问题作为学术兴趣.

解决方法

我会试着回答我自己的问题.

该主题有点误导,实际上根本没有对val x的表达式应用隐式转换. Null是String的子类型,Int具有方法abstract def(x:String):String,因此它也可以应用于Null.

Xprint:typer的输出也证实了这一点,因为它应该显示所有隐式转换,并且显然它没有为x的表达式显示任何内容.

并回答“是否有启用implcit nullToInt的方法”的问题,启用它的唯一方法是在这种情况下明确指定,因为编译器在没有它们的情况下成功编译代码时不会考虑使用任何含义.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读