IT-Sheriff
IT-Sheriff

Reputation: 164

Groovy: how to access inner variables?

I am trying to access a variable which is getting defined inside a loop. How can I access it?

fileContents.split('\n').each {
    if (it =~ /nodePort:/) {
        def splitted_string = it.split(':')
        String nodePort = (splitted_string[1].trim())
    }
}
println nodePort

Error: groovy.lang.MissingPropertyException: No such property: nodePort

How do I access variable nodePort?

Upvotes: 0

Views: 77

Answers (2)

tim_yates
tim_yates

Reputation: 171154

Another option is:

fileContents.split('\n').find { it =~ /nodePort:/ }?.tokenize(":")?.getAt(1)

Upvotes: 0

Mene
Mene

Reputation: 3809

You cannot access variables from the outer scope. However, you can move the variable to the outer scope.

String nodePort
fileContents.split('\n').each {
    if (it =~ /nodePort:/) {
        nodePort = (splitted_string[1].trim())
    }
}
println nodePort

Upvotes: 1

Related Questions