开发者

Groovy Console not outputing old values

I've got a weird problem while testing some code in Groovy Console. The following code:

class GameCharacter
{
    def hp
    def mp
    def showInfo
}

c = new GameCharacter(hp: 0, mp: 0)

c.showInfo = {println "HP: ${hp} | MP: ${mp}"}

c.showInfo()

c.with{hp = 100 ; mp = 90}

c.showInfo()

Gives me followi开发者_StackOverflow社区ng output:

HP: 100 | MP: 90
HP: 100 | MP: 90

Why the first p.showInfo() call didn't show me the first zeroed values?


I am actually surprised this code works for you. I get this exception in Groovy Console:

Exception thrown
Mar 30, 2011 2:40:47 PM org.codehaus.groovy.runtime.StackTraceUtils sanitize
WARNING: Sanitizing stacktrace:
groovy.lang.MissingPropertyException: No such property: hp for class: ConsoleScript0

So it looks to me like showInfo is supposed to print the fields you have in GameCharacter. To fix your code you can either a) assign the closure within the class GameCharacter:

class GameCharacter
{
    def hp
    def mp
    def showInfo = {println "HP: ${hp} | MP: ${mp}"}
}

or b) you can add the closure via meta programming if you want to add it later:

class GameCharacter
{
    def hp
    def mp
}

c.metaClass.showInfo = {println "HP: ${hp} | MP: ${mp}"}

You'll get the correct result for both implementation:

HP: 0 | MP: 0
HP: 100 | MP: 90
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜