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

scala – 本地分配会影响类型吗?

发布时间:2020-12-16 19:00:40 所属栏目:安全 来源:网络整理
导读:在以下示例中,f3可以采用Iterable [Array [Int]] def f3(o:Iterable[Iterable[Any]]):Unit = {} f3(Iterable(Array(123))) // OK. Takes Iterable[Array[Int]] 但是如果我将Iterable [Array [Int]]赋给局部变量,它不能: val v3 = Iterable(Array(123)) f3(v
在以下示例中,f3可以采用Iterable [Array [Int]]

def f3(o:Iterable[Iterable[Any]]):Unit = {}

  f3(Iterable(Array(123)))    // OK. Takes Iterable[Array[Int]]

但是如果我将Iterable [Array [Int]]赋给局部变量,它不能:

val v3 = Iterable(Array(123))
  f3(v3)    // Fails to take Takes Iterable[Array[Int]]

有错误:

Error:(918,10) type mismatch;
  found   : Iterable[Array[Int]]
  required: Iterable[Iterable[Any]]
  f3(x)

什么是软糖?为什么第一个例子工作,但不是秒.它似乎与嵌套泛型有关:

def f(o:Iterable[Any]):Unit = {}
  f( Array(123))
  val v1 = Array(123)
  f(v1)  // OK

  def f2(o:Iterable[Any]):Unit = {}
  f2( Iterable(Array(123)))
  val v2 = Array(123)
  f(v2) // OK

用scala.2.11

解决方法

首先,重要的是Array不扩展Iterable(因为它是Java类型).而是存在从Array [A]到Iterable [A]的隐式转换,因此期望的类型很重要.

在第一种情况下:Iterable(Array(123))是f3的参数,因此使用期望类型Iterable [Iterable [Any]]进行类型检查.所以Array(123)是用预期类型Iterable [Any]进行类型检查的.好吧,它的实际类型是Array [Int],编译器插入转换(因为Iterable [Int]符合Iterable [Any]).所以这实际上是Iterable(array2iterable(Array(123))(我不记得确切的名字).

在第二种情况下,f3的类型为Iterable [Array [Int]]:在val f3 = …行中没有任何东西可以触发隐式转换,对吧?并且没有从Iterable [Array [Int]]到Iterable [Iterable [Int]]的隐式转换(或者,当从A到B的隐式转换时,更一般地从Iterable [A]到Iterable [B]),所以下一行无法编译.您可以自己编写此转换,但它不会有帮助,例如将Array [Array [Int]]转换为Iterable [Iterable [Int]].

当然,如果你使用Iterable [Any],再没有什么可以触发隐式转换!

(编辑:李大同)

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

    推荐文章
      热点阅读