0

I'm always battling eclipse underlining properties or methods called upon objects I reference using bracket notation. Here's a simple example. Looking for most efficient and succinct way to tell compiler that this is a file, and therefor .write is valid, and so don't underline it.

For novice readers, I'm making a map on the fly to add the file and it's contents to the arraylist.

def myOutputList = new ArrayList()
def myFileObject = new File("outputFile.txt")
def myFileContents = "Whargarble"

myOutputList.add([
    file:myFileObject,
    contents:myFileContents
])

myOutputList.each{
    it['file'].write(it['contents'])
}
solvingJ
  • 1,321
  • 1
  • 19
  • 30

3 Answers3

1

You can state the type explicitly - then Eclipse will cooperate.

In your example:

File f = it['file']
f.write...

You can also use a class instead of a map (again, with explicit types)

dmahapatro
  • 49,365
  • 7
  • 88
  • 117
Raz Abramov
  • 181
  • 12
0

If you need collections of pairs, why don't you use map instead of list? :) But be aware that keys are unique in map.

def myOutputMap = [:]
def myFileObject = new File("outputFile.txt")
def myFileContents = "Whargarble"

myOutputMap[myFileObject] = myFileContents

myOutputMap.each { file, content ->
    file.write(content)
}

If Eclipse will still complain about type, define type

myOutputMap.each { File file, String content ->
    file.write(content)
}

If you want to stay with lists, you might try Raz suggestion.

And one more small thing.

def myOutputList = []

Is much nicer way to define ArrayList! :)

Jakub Dyszkiewicz
  • 524
  • 1
  • 5
  • 17
  • First... thank you for your feedback and input. I was using a map, it was within the arraylist, which I even stated. Please read more carefully in future. Your suggestion is a different structure altogether, which would not be suitable for more than 1 item, such as a list of files and their contents. Also, I actually prefer the verbose ArrayList() syntax. Thanks for the tip though. – solvingJ Dec 30 '15 at 23:18
0

The answer posted by Raz Abramov is a good solution. I do wish there was an "inline" way to do it. I did find one such way (below) but I prefer your way in this case.

it['file'].invokeMethod('write',(it['contents']))

Also, for those wondering, I tested Raz's solution to make sure it wasn't copying the file object into a new variable (and also, not a new one each time it loops). It was not making any copies. This method creates a temporary pointer to the current it['file'] object and is therefor is very efficient as one would hope. Thanks again Raz.

myOutputList.each{
    File f = it['file']
    assert myFileObject.is(f)
}
solvingJ
  • 1,321
  • 1
  • 19
  • 30