2011-08-01 9 views

답변

5

스칼라는 정적 언어이므로 모든 코드가 컴파일 타임에 존재해야합니다. 그러나 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 

방법을 할 수 있습니다.

관련 문제