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

scala – 将隐式转换应用于地图

发布时间:2020-12-16 09:51:36 所属栏目:安全 来源:网络整理
导读:我在以下示例中尝试了隐式转换: val m: Map[Int,Int] = Map(10 - "asd") //fineval mm: Map[Int,Int] = Map("asd" - 20) //type mismatch; found: (String,Int) //required: (Int,Int)implicit def stringToInt(str: String): Int = 10 为什么我们不能将隐
我在以下示例中尝试了隐式转换:

val m: Map[Int,Int] = Map(10 -> "asd")  //fine
val mm: Map[Int,Int] = Map("asd" -> 20) //type mismatch; found: (String,Int) 
                                         //required: (Int,Int)

implicit def stringToInt(str: String): Int = 10

为什么我们不能将隐式转换应用于映射键?有办法解决这个问题吗?

解决方法

它不起作用,因为你正在使用 – >这是一个(内联)运算符:

implicit final class ArrowAssoc[A](self : A) extends scala.AnyVal {
  @scala.inline
  def ->[B](y : B) : scala.Tuple2[A,B] = { /* compiled code */ }
  def →[B](y : B) : scala.Tuple2[A,B] = { /* compiled code */ }
}

您可以看到,在评估B时,A已经“固定”.我们只是说,在使用时,您只能(隐式)转换元组的右侧 – >操作符:

implicit def stringToInt(str: String): Int = 10  
implicit def intToStr(str: Int): String = "a"

val a: Map[Int,Int] = Map(10 -> "asd") //fine
val b: Map[Int,Int] = Map("asd" -> 20) // error! cant change left side

val c: Map[String,String] = Map("asd" -> 20) // fine 
val d: Map[String,String] = Map(10 -> "asd") // error! cant change left side

由于与使用运算符相关的类似编译器怪癖 – >,@ Jorg的解决方案在一个方向上工作,而在另一个方向上工作:

implicit def tupleIntifier(t: (String,Int)) = (10,10)
implicit def tupleIntifier2(t: (Int,String)) = (10,10)

val a: Map[Int,Int] = Map("asd" -> 20) // uses tupleIntifier
val b: Map[Int,Int] = Map(10 -> "asd") // fails!!

但是,如果您避免使用 – >运算符完全简单地使用(键,值)语法,它将起作用:

val a: Map[Int,Int] = Map((10,"asd"))
val b: Map[Int,Int] = Map(("asd",20))

implicit def stringToInt(str: String): Int = 15

println(a) // prints Map(10 -> 15)
println(b) // prints Map(15 -> 20)

(编辑:李大同)

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

    推荐文章
      热点阅读