gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:50:01 25 4
gpt4 key购买 nike

我写

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

然后就可以了。

从 Odersky 的 Scala 编程 中,我发现不需要导入源或预期目标类型的伴生对象中的隐式转换。

最佳答案

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 内)从 IntFraction 的隐式转换,如果有的话,因为那是源类型)。

关于scala - 隐式转换,是否需要导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4569192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com