Skip to content

COM Methods and Properties in Scriptom

Keegan Witt edited this page Jul 23, 2015 · 2 revisions

Method Syntax

The syntax for calling a method on an ActiveXObject is (mostly) the same as calling a method on any other Groovy object. The only caveat is that optional parameters may be omitted, or you can specify Scriptom.MISSING to indicate that an optional parameter is not defined.

def voice = new ActiveXObject('SAPI.SpVoice');
voice.Speak('It's all GROOVY, man!');

Property Syntax

In Groovy, which follows the JavaBean model, properties don't have indexes. There are lots of COM properties without indexes, and they work the same way. In the code example below, the voice.Status property returns an ActiveXObject, and the RunningState property returns an integer flag.

def voice = new ActiveXObject('SAPI.SpVoice')
voice.Speak 'GROOVY and SCRIPT um make com automation simple, fun, and groovy, man!', SpeechVoiceSpeakFlags.SVSFlagsAsync
while(voice.Status.RunningState != SpeechRunState.SRSEDone)
{
  ...
}

COM also supports parameterized (or 'indexed') properties. Indexed COM properties look like an array, list, or a map. Properties may be read from or written to, but they do not represent standalone objects (that's not an array you are working with). In some cases, properties have more than one index. The following practical example sets the value of the first column in an Excel spreadsheet to a date value (alternately, a Java Date could have been used).

worksheet.Cells.Item[row+1,1] = "$row/1/2007"

Yep, that's a property!

Maybe We Made It too Flexible?

Methods and a property getters (both non-indexed and indexed) are pretty much the same thing, and in most cases, they are interchangeable. So the following two lines of code do the same thing:

println worksheet.Cells.Item[row+1,1]
println worksheet.Cells.Item(row+1,1)

Indexed properties don't work if all the parameters are optional. This doesn't normally happen in the real world (why would you do that?), but it is possible. To support this unlikely scenario, there is an alternate syntax for accessing properties as methods:

To get a property value, simply call it as a method. Alternately (to match setter syntax), you can prefix the property name with _get. To set a property value, prefix the property name with _set or _put. The last argument passed to the method is the value.

//Getters, all equivalent.
println worksheet.Cells.Item[row+1,1]
println worksheet.Cells.Item(row+1,1)
println worksheet.Cells._getItem(row+1,1)

//Setters, all equivalent.
worksheet.Cells.Item[row+1,1] = new Date()
worksheet.Cells._setItem(row+1,1, new Date())
worksheet.Cells._putItem(row+1,1, new Date())

The method syntax is actually a little faster than the bracketed property syntax, but we recommend that you use the syntax that makes your intentions most evident.