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

scala – 隐式转换,是否需要导入?

发布时间:2020-12-16 09:21:50 所属栏目:安全 来源:网络整理
导读:我写 object MyString { implicit def stringToMyString(s: String) = new MyString(s) }class MyString(str: String) { def camelize = str.split("_").map(_.capitalize).mkString override def toString = str}object Parse { def main(args: Array[Strin
我写

object MyString {
  implicit def stringToMyString(s: String) = new MyString(s)    
}

class MyString(str: String) {
  def camelize = str.split("_").map(_.capitalize).mkString

  override def toString = str
}


object Parse {
  def main(args: Array[String]) {
    val x = "active_record".camelize
    // ...
  }
}

在我的程序这会导致编译错误.我插入后

import MyString.stringToMyString

然后它工作.

从Scala中的Odersky的编程我得到源或预期目标类型的伴随对象中的隐式转换不需要导入.

解决方法

implicit conversion in the companion
object of the source or expected
target types don’t need to be
imported.

真的够现在,方法camelize是在类MyString上定义的,实际上,在对象伴侣中有一个隐含的MyString转换.但是,代码中没有任何内容告诉编译器MyString是预期的目标类型.

如果相反,你写这个:

val x = ("active_record": MyString).camelize

那么它会工作,因为编译器会知道你期望“active_record”是一个MyString,使其查找对象MyString内的隐式转换.

这可能看起来有点限制,但它实际上在许多地方有效.比方说,你有:

class Fraction(num: Int,denom: Int) {
    ...
    def +(b: Fraction) = ...
    ...
}

然后你有一个这样的代码:

val x: Fraction = ...
val y = x + 5

现在,x确实有一个方法,其预期类型是Fraction.因此,编译器将会看到,在对象Fraction(和对象Int内部,如果有一个,因为那是源类型)内部的Int到Fraction的隐式转换.

(编辑:李大同)

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

    推荐文章
      热点阅读