/tutorial/downcasting.e

http://github.com/tybor/Liberty · Specman e · 55 lines · 36 code · 8 blank · 11 comment · 3 complexity · 04ee459fc2b03a666fdbf46ed9985208 MD5 · raw file

  1. class 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. create {ANY}
  7. make
  8. feature {}
  9. make
  10. local
  11. a: ABSTRACT_STRING; s: STRING; col: COLLECTION[INTEGER]; array: ARRAY[INTEGER]
  12. do
  13. s := "Hello%N"
  14. a := s -- standard valid assignment
  15. s ?= a -- Try to put `a' in `s' if it is a STRING or subtype. `s' is Void if assignment fails.
  16. if s /= Void then
  17. std_output.put_string(s)
  18. else
  19. std_output.put_string(once "Void")
  20. end
  21. if s ?:= a then
  22. -- Could `a' be assigned to `s'?
  23. std_output.put_string(once "We can put `a' in `s'.%N")
  24. s ::= a -- force the assignment because we know it's allowed (it's a require of `::=' operator)
  25. else
  26. std_output.put_string(once "`a' cannot be put in `s'.%N")
  27. end
  28. if {STRING} ?:= a then
  29. -- Could `a' be assigned to a STRING? (very useful in assertions)
  30. std_output.put_string(once "`a' is a STRING.%N")
  31. s ::= a -- force the assignment because we know it's allowed (it's a require of `::=' operator)
  32. else
  33. std_output.put_string(once "`a' is not a STRING.%N")
  34. end
  35. col := {ARRAY[INTEGER] 1, << 1, 2, 3 >> }
  36. -- see tutorial/manifest_expression.e
  37. -- Sometimes, thanks to the way the system is built, the type
  38. -- known so we are sure the assignment is always valid.
  39. -- In this case, we don't need to do an assignment attempt
  40. -- with `?=', the test is a waste of time. `::=' is the solution.
  41. array ?= col -- Standard common pattern
  42. check
  43. array /= Void
  44. end
  45. array ::= col -- New way.
  46. end
  47. end -- class DOWNCASTING