使用scala隐式将方法添加到库中
我想将新函数“extra”添加到库类(例如“orig”) 稍微修改一下,只需函数名(我真正想要的)和:-(糟糕使用scala隐式将方法添加到库中,scala,implicit-conversion,Scala,Implicit Conversion,我想将新函数“extra”添加到库类(例如“orig”) 稍微修改一下,只需函数名(我真正想要的)和:-(糟糕 对象容器{ A类(val n:Int){ def hello(其他:A)=新A(n+其他.n) } 对象A{ 隐式def fromInt(n:Int)=新的A(n) } //这将成为可能: 1.你好(新A(1)) //因为它被转换为: A.fromInt(1)。你好(新的A(1)) } :16:错误:值hello不是Int的成员 1.你好(新A(1)) Scala版本2.9.1.r0
对象容器{
A类(val n:Int){
def hello(其他:A)=新A(n+其他.n)
}
对象A{
隐式def fromInt(n:Int)=新的A(n)
}
//这将成为可能:
1.你好(新A(1))
//因为它被转换为:
A.fromInt(1)。你好(新的A(1))
}
:16:错误:值hello不是Int的成员
1.你好(新A(1))
Scala版本2.9.1.r0-b20120114153402(OpenJDK 64位服务器虚拟机,Java 1.6.0_22)
这有点让人困惑。我试着混音
7.3意见
谢谢问题可能是加载顺序,
orig
和rich
,或者rich
和隐式def
顺便说一句,以下代码工作正常,我首先定义了orig
而不是rich
,最后将implicit
转换应用到pimporig
object container {
object orig {
def standard(s:String) = "standard"
}
object rich {
case class Arg(val some: String = "some")
object Arg {
implicit def orig2rich(o: orig.type) = new { def extra(a: Arg) = "extra" }
}
}
implicit def orig2rich(o: orig.type) = new { def extra(a: rich.Arg) = "extra" }
orig.extra(rich.Arg())
}
println(container.orig.extra(container.rich.Arg()))
scala正在应用在同一范围内可见的隐式转换,所以您只需添加行即可
import rich.orig2rich
或
此代码将起作用
object container {
//implicit def orig2rich(o: orig.type) = new { def extra(a: rich.Arg) = "extra" }
object rich {
implicit def orig2rich(o: orig.type) = new {
def extra(a: Arg) = "extra"
}
case class Arg(val some: String = "some")
object Arg {
implicit def orig2rich(o: orig.type) = new {
def extra(a: Arg) = "extra"
}
}
}
object orig {
def standard(s: String) = "standard"
}
import rich.orig2rich
def test = orig.extra(rich.Arg())
}
println(container.test)
请阅读以下内容:
object container {
class A(val n: Int) {
def hello(other: A) = new A(n + other.n)
}
object A {
implicit def fromInt(n: Int) = new A(n)
}
// This becomes possible:
1.hello(new A(1))
// because it is converted into this:
A.fromInt(1).hello(new A(1))
}
<console>:16: error: value hello is not a member of Int
1.hello(new A(1))
object container {
object orig {
def standard(s:String) = "standard"
}
object rich {
case class Arg(val some: String = "some")
object Arg {
implicit def orig2rich(o: orig.type) = new { def extra(a: Arg) = "extra" }
}
}
implicit def orig2rich(o: orig.type) = new { def extra(a: rich.Arg) = "extra" }
orig.extra(rich.Arg())
}
println(container.orig.extra(container.rich.Arg()))
import rich.orig2rich
import rich._
object container {
//implicit def orig2rich(o: orig.type) = new { def extra(a: rich.Arg) = "extra" }
object rich {
implicit def orig2rich(o: orig.type) = new {
def extra(a: Arg) = "extra"
}
case class Arg(val some: String = "some")
object Arg {
implicit def orig2rich(o: orig.type) = new {
def extra(a: Arg) = "extra"
}
}
}
object orig {
def standard(s: String) = "standard"
}
import rich.orig2rich
def test = orig.extra(rich.Arg())
}
println(container.test)