Scala类创建后能够被修改吗?

3
2个回答

5
Scala是一种静态语言,因此所有代码都应该在编译时存在。但是,您可以使用Pimp-My-Library方法模拟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)"

4

您可以做到

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

在创建实例之后,方法本身是无法更改的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接