隐式转换,是否需要导入? [英] Implicit conversion, import required or not?

查看:140
本文介绍了隐式转换,是否需要导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写

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
    // ...
  }
}

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

in my program. This causes a compiling error. After I inserted

  import MyString.stringToMyString

然后它起作用.

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

From Odersky's Programming in Scala I got that implicit conversion in the companion object of the source or expected target types don't need to be imported.

推荐答案

随播广告中的

隐式转换 源或预期的对象 目标类型不必是

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

真的.现在,方法camelize是在类MyString上定义的,并且确实在其对象伴侣中存在对MyString的隐式转换.但是,代码中没有任何内容告诉编译器MyString expected 目标类型.

True enough. Now, the method camelize is defined on the class MyString, and, indeed, there is an implicit conversion to MyString inside its object companion. However, there is nothing in the code telling the compiler that MyString is the expected target type.

相反,如果您是这样写的:

If, instead, you wrote this:

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

然后它会工作,因为编译器会知道您期望 "active_record"MyString,从而使它可以查找对象MyString中的隐式转换.

then it would work, because the compiler would know you expect "active_record" to be a MyString, making it look up the implicit conversion inside object MyString.

这可能看起来有点限制性,但实际上它可以在许多地方使用.举例来说,您有:

This might look a bit restrictive, but it actually works in a number of places. Say, for instance, you had:

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

然后您得到了这样的代码:

And then you had a code like this:

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

现在,x确实有一个+方法,其预期类型Fraction.因此,编译器将在此处查找对象Fraction内部(以及对象Int内部(如果有的话,因为这是源类型))从IntFraction的隐式转换.

Now, x does have a + method, whose expected type is Fraction. So the compiler would look, here, for an implicit conversion from Int to Fraction inside the object Fraction (and inside the object Int, if there was one, since that's the source type).

这篇关于隐式转换,是否需要导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆