具体地说,我在这里考虑了与6.3等效的功能:
http://www.siafoo.net/article/52
发布于 2011-08-01 16:11:21
Scala是一种静态语言,因此所有代码都应该在编译时存在。但是,您可以使用方法模拟python特性,将方法添加到现有类中,而无需修改类本身。但是,您不能更改现有方法。示例:
class Foo( val i: Int )
class RichFoo( f: Foo ) {
def prettyPrint = "Foo(" + i + ")"
}
implicit def enrichFoo( f: Foo ) = new RichFoo(f)
val foo = new Foo( 667 )
println( foo.prettyPrint ) // Outputs "Foo(667)"发布于 2011-08-01 15:31:22
你可以这样做
class Class {
var method = () => println("Hey, a method (actually, a function bound to a var)")
}
val instance = new Class()
instance.method()
// Hey, a method (actually, a function bound to a var)
val new_method = () => println("New function")
instance.method = new_method
instance.method()
// New function创建实例后,无法更改方法本身。
https://stackoverflow.com/questions/6895334
复制相似问题