我有地图
def loginEmail = [
"abc": "abc@mail.ru",
"cde": "cde@mail.ru"
]
如何从方法中获得价值? 像这样:
def getEmail(String login){
return loginEmail.get(login)
}
答案 0 :(得分:2)
在Groovy控制台中尝试您的代码时,出现以下错误:
Exception thrown
groovy.lang.MissingPropertyException: No such property: loginEmail for class: ConsoleScript9
at ConsoleScript9.getEmail(ConsoleScript9:7)
at ConsoleScript9.run(ConsoleScript9:10)
我想到了两种解决方法。您可以同时传递键和映射,以便可以从方法中返回相应的值。像这样:
def loginEmail = [
"abc": "abc@mail.ru",
"cde": "cde@mail.ru"
]
def getEmail(String login, Map<String, String> loginEmail){
return loginEmail[login]
}
def result = getEmail("abc", loginEmail)
println(result)
或者将地图设为类的属性,然后通过类方法调用它,例如:
class TestLogin {
static loginEmail = [
"abc": "abc@mail.ru",
"cde": "cde@mail.ru"
]
static getEmail(String login){
return loginEmail[login]
}
}
TestLogin.getEmail('abc')
答案 1 :(得分:2)
还可以使用:
def loginEmail = [
"abc": "abc@mail.ru",
"cde": "cde@mail.ru"
]
def getEmail(login) {
loginEmail."$login"
}
答案 2 :(得分:1)
我认为您是在询问Groovy中的范围问题。 如果是,请在下面找到答案
def val1 = "hi" // This can't be used inside a method
val2 = "hai" // This can be used as it is global
因此,在您的情况下,将map声明为
loginEmail = [
"abc": "abc@mail.ru",
"cde": "cde@mail.ru"
]
而不是def loginEmail
。
希望这会有所帮助。
答案 3 :(得分:1)
您的代码应该可以工作,除非您遇到一些范围问题。
以下示例显示了与https://stackblitz.com/edit/angular-shared-fail测试结合使用的有效实现。
package x.y.z
import spock.lang.Specification
class LoginLockupSpec extends Specification {
def "test different ways to lookup email by login"() {
given:
def loginLookup = new LoginLookup()
expect: 'getMail Method returns mail'
loginLookup.getEmail('abc') == "abc@mail.ru"
and: 'direct map access is also possible'
loginLookup.loginEmail.abc == "abc@mail.ru"
loginLookup.loginEmail['cde'] == "cde@mail.ru"
loginLookup.loginEmail.get('cde') == "cde@mail.ru"
}
}
class LoginLookup {
def loginEmail = [
"abc": "abc@mail.ru",
"cde": "cde@mail.ru"
]
def getEmail(String login) {
return loginEmail.get(login)
}
}