问题描述
我觉得我缺少Groovy处理字符串的方式.我意识到它们是不可变的,但是我想做的是在运行时内插一个值.我不知道怎么办.让我用Python给出一个非常简单的示例(作为可执行伪代码")来说明我的意思.然后,我将给出我在Groovy中尝试过的内容.
I feel like I'm missing something with how Groovy handles strings. I realize that they're immutable, but what I would like to do is interpolate a value at runtime. I can't figure out how. Let me give a really simple example in Python (as "executable pseudo-code") to illustrate what I mean. Then I'll give what I've tried in Groovy.
Python
# string_sample.py
class MyClass(object):
greeting = 'Hello, %s!'
def __init__(self):
object.__init__(self)
def sayHello(self, name):
print self.greeting % name
if __name__ == '__main__':
m = MyClass()
m.sayHello('Mario')
上面的照片:你好,马里奥!
时髦
// string_sample.groovy
class MyClass {
def greeting = "Hello, ${name}!"
MyClass() {
}
void sayHello(name) {
println greeting
}
}
m = new MyClass()
m.sayHello('Mario')
上面的Groovy脚本抱怨name
是未知的:
The above Groovy script complains that name
is unknown:
Caught: groovy.lang.MissingPropertyException: No such property: name for class: MyClass
我了解正在发生的事情以及原因.我只是不确定该怎么办.我意识到可以使用String.format
,这还不错:
I understand what's happening and why. I'm just not sure what to do about it. I realize that String.format
can be used, which isn't so bad:
String greeting = "Hello, %s!"
// Omitted...
void sayHello(name) {
println String.format(greeting, name)
}
我只是在想,也许有一种 groovier 的方式.有人知道吗谢谢!
I'm just thinking that maybe there's a groovier way of doing it. Anyone know? Thanks!
推荐答案
您可以使用闭包:
class MyClass {
def greeting = { name -> "Hello, ${name}!" }
MyClass() {
}
void sayHello(name) {
println greeting(name)
}
}
这篇关于Groovy字符串插值,其值仅在运行时已知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!