Blake Simmons
Blake Simmons

Reputation: 466

How can I rectify static scope error when referencing a static variable in my groovy script?

I have a script which exports excel worksheets to csv, and I am attempting to escape commas, quotes and the like. I have created a static method that encodes the value of the cell being accessed. This method references a static variable which stores a Pattern.compile() value.

I have tried using def rxquote within the method but this gives me a different error stating that using static modifier before declaring my rxquote variable is illegal. Code is below followed by error message.

#!/usr/bin/env groovy
@Grab(group = 'org.apache.poi', module = 'poi', version = '4.1.0')
@Grab(group = 'org.apache.poi', module = 'poi-ooxml', version = '4.1.0')

import java.util.regex.*
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.apache.poi.ss.usermodel.*

static Pattern rxquote = Pattern.compile("\"")
static private String encodeValue(String value) {
    boolean needQuotes = false;
    if ( value.indexOf(',') != -1 || value.indexOf('"') != -1 ||
         value.indexOf('\n') != -1 || value.indexOf('\r') != -1 ){
        needQuotes = true;
    }
    Matcher m = rxquote.matcher(value)
    if ( m.find() ) {
        needQuotes = true
        value = m.replaceAll("\"\"")
    }
    if ( needQuotes ) {
        return "\"" + value + "\""
    } 
        else return value;
    }

//for(){
//   ... export csv code (which works on its own)
//}

Error message on compile:

Apparent variable 'rxquote' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'rxquote' but left out brackets in a place not allowed by the grammar.
 @ line 27, column 17.
       Matcher m = rxquote.matcher(value);
                   ^

I've tried researching the issue and have found several similar questions here, but none of the solutions appear to apply to this situation as far as I can tell. I expected a static declaration of the variable to avoid this problem, but it seems there's something I'm missing.

Upvotes: 0

Views: 779

Answers (1)

daggett
daggett

Reputation: 28564

you can't declare static variable in groovy script.

it's allowed only in groovy/java class.

error does not correspond to situation.

should be : Modifier 'static' not allowed here.

as workaround for static variables you can use some class:

class Const{
    static String bar = 'test'
}

static private String foo() {
    return Const.bar
}

foo()

Upvotes: 1

Related Questions