Can Scala classes be modified after creation?
Specifically I was thinking about equivalent functionality to 6.3 here:
http://www开发者_如何学运维.siafoo.net/article/52
Scala is a static language and thus all code should exists at compile time. However, you can simulate the python feature using the Pimp-My-Library approach to add methods to existing class, without modifying the class itself. However, you cannot change an existing method. Example:
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)"
You could do
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
Methods themselves cannot be changed after the instance has been created.
精彩评论