Section 15.1. Implicit Coercion

15.1. Implicit Coercion

In Chapter 14, I explained coercion and described the coercions that are possible between built-in datatypes in the AppleScript language. Binary operators can (and will) perform coercion without your specifically asking for it. This is called implicit coercion , and is one of the most confusing aspects of AppleScriptand a frequent source of mistakes in scripts. If you are not prepared for what implicit coercions an operator will perform, you will be surprised when the result of an operation is not what you expected. That's why this chapter spends so much time on the implicit coercions performed by the various operators.

What coercions AppleScript will perform implicitly is not the same as what coercions you can get it to perform explicitly (with the as operator). AppleScript's error messages in this regard can add to the confusion. For example:

 1 and 1 -- compile-time error: Can't make 1 into type boolean 

That error message, on its face, is lying. AppleScript can make 1 into a boolean. What AppleScript really means by the error message here is: "In order for me to perform this operation, I would need to coerce the first 1 (before the and) to a boolean, implicitly; and I refuse to do that." Even weirder is what happens when you proceed to coerce the first 1 to a boolean explicitly:

 1 as boolean and 1 -- true 

It workswhich means that even though AppleScript refused to coerce the first 1 to a boolean implicitly, it now happily coerces the second 1 to a boolean implicitly!

But do not imagine that there is some simple rule governing this behavior (such as that AppleScript never coerces the first operand implicitly). In this next example, AppleScript happily coerces both operands implicitly (to a number ):

 "3" + "4" -- 7 

You see now why the rules for implicit coercion need to be made explicit.

AppleScript. The Definitive Guide
AppleScript: The Definitive Guide, 2nd Edition
ISBN: 0596102119
EAN: 2147483647
Year: 2006
Pages: 267
Authors: Matt Neuburg

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: