且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-09-18 11:33:22

随播广告中的

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

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).