Automatic Object Conversion

I happened upon something in the AppleScript Language Guide that I found of interest and thought I’d pass it along FWIW. It’s probably old news to many forum members but perhaps not to new members.

For the reasons cited, I would not expect any of the following to work:

-- POSIX path is a property of an alias
POSIX path of "Macintosh HD:Users:Robert:" --> "/Users/Robert/"

--the duplicate command requires objects
tell application "Finder"
	duplicate "Macintosh HD:Users:Robert:Working:Test Text.txt" to "Macintosh HD:Users:Robert:Desktop:"
end tell

--the concatenation operator concatenates text objects
set myVariable to "Route " & 66 --> "Route 66"

The reason they do work (if my understanding is correct) is automatic object conversion:

Coercion (also known as object conversion) is the process of converting objects from one class to another. AppleScript converts an object to a different class in either of these circumstances:

  • in response to the as operator
  • automatically, when an object is of a different class than was expected for a particular command or operation

I ran some timing tests and there can be a minuscule advantage to relying on automatic object conversion. Whether one uses it or not, It’s good to know why things work as they do.

1 Like

AppleScript can make some pretty good guesses about what you are trying to do. Then again, sometimes it gets pedantic, so you have to hit it in the head with a rock (this is the part that keeps scripters from having too much hair).

A tell statement probably uses similar magic. For example, when using text, doing something like text 1 thru -1 assumes that the object you are wanting to use is the target.

The concatenation operator also works with lists, so the class of the first item is what AppleScript guesses you want to use it for. For example, swap the items in your sample and you will get {66, "Route "}. This is also where the idea of using something like "" & true as a shortcut for coercing to text comes from.