/tutorial/downcasting.e
Specman e | 55 lines | 36 code | 8 blank | 11 comment | 3 complexity | 04ee459fc2b03a666fdbf46ed9985208 MD5 | raw file
1class DOWNCASTING 2 -- 3 -- This tutorial presents various examples allowing safe downcasting (the way you can assign an object 4 -- of a general type into some more specific one). 5 -- 6 7create {ANY} 8 make 9 10feature {} 11 make 12 local 13 a: ABSTRACT_STRING; s: STRING; col: COLLECTION[INTEGER]; array: ARRAY[INTEGER] 14 do 15 s := "Hello%N" 16 a := s -- standard valid assignment 17 18 s ?= a -- Try to put `a' in `s' if it is a STRING or subtype. `s' is Void if assignment fails. 19 if s /= Void then 20 std_output.put_string(s) 21 else 22 std_output.put_string(once "Void") 23 end 24 25 if s ?:= a then 26 -- Could `a' be assigned to `s'? 27 std_output.put_string(once "We can put `a' in `s'.%N") 28 s ::= a -- force the assignment because we know it's allowed (it's a require of `::=' operator) 29 else 30 std_output.put_string(once "`a' cannot be put in `s'.%N") 31 end 32 33 if {STRING} ?:= a then 34 -- Could `a' be assigned to a STRING? (very useful in assertions) 35 std_output.put_string(once "`a' is a STRING.%N") 36 s ::= a -- force the assignment because we know it's allowed (it's a require of `::=' operator) 37 else 38 std_output.put_string(once "`a' is not a STRING.%N") 39 end 40 41 col := {ARRAY[INTEGER] 1, << 1, 2, 3 >> } 42 -- see tutorial/manifest_expression.e 43 -- Sometimes, thanks to the way the system is built, the type 44 -- known so we are sure the assignment is always valid. 45 -- In this case, we don't need to do an assignment attempt 46 -- with `?=', the test is a waste of time. `::=' is the solution. 47 48 array ?= col -- Standard common pattern 49 check 50 array /= Void 51 end 52 array ::= col -- New way. 53 end 54 55end -- class DOWNCASTING