[ Team LiB ] |
14.1 Implicit CoercionWhen you supply a value where a value of another datatype is expected, AppleScript may coerce silently if possible. This is called implicit coercion, and it takes place in connection with AppleScript's operators. These operators have definite rules about what datatypes they expect, and what implicit coercions they will perform if other datatypes are provided. Details appear in Chapter 15. No implicit coercion takes place when assigning a value to a variable, because variables have no declared datatype; the variable simply adopts the new value. No implicit coercion takes place when passing a parameter, because handlers and commands do not provide prototypes specifying a particular datatype. This is not to say that a handler or command cannot itself perform a coercion if it receives one datatype and prefers another. It can. But then the coercion is not necessarily implicit, and it isn't necessarily being performed by AppleScript. For example, suppose you say this: tell application "Finder" set name of folder 1 to 6 -- error: "Can't make some data into the expected type." end tell The Finder's dictionary says very plainly what the Finder expects as the name of a folder—it expects Unicode text. But AppleScript does not look at the dictionary and then perform an implicit coercion; it just sends the Finder what you said to send it. It is then up to the Finder to decide whether it's happy with what was sent. In this particular case, the Finder is not happy, and it lets you know with an error. Now suppose you say this: tell application "Finder" set name of folder 1 to "6" end tell Now the Finder happily performs a coercion, and you never hear about it. The Finder expects Unicode text, and you sent a string. The Finder coerces the string to Unicode text, so the difference is never evident to you; it's all handled transparently. An application's dictionary doesn't necessarily say what implicit coercions the application will perform. The Finder's dictionary didn't say, "I'd like Unicode text but I'll accept a string, and no numbers, please"; it said "Unicode text," period. Typically, to find out whether an application will accept a datatype other than what its dictionary specifies, you just have to try it and see (Section 19.5.7). Handlers that you write are not protected by any mechanism such as prototypes or datatype declarations in their definition from receiving parameters with undesirable datatypes. If your handler has reason to be choosy about what sorts of values it's willing to accept, then it needs to test those values and respond accordingly. For example: on sendMeAString(s) if {class of s} is not in {string, Unicode text} then error "Can't make some data into the expected type." end if ... end sendMeAString |
[ Team LiB ] |