# Something to show off casting and parsing # Casting can only be done between sub/super class types - redirects a polymorphic # object Type to something it already is, either less or more specific. # (up or down the class inheritance hierarchy) # # parsing is a conversion - usually from a String representation to Type # e.g StringToInt, StringToDecimal, StringToComplex, StringToParserToken class BaseString """ Simple String baseclass """ var _str as String def init(value as String) _str = value def count as int return _str.length class AugString inherits BaseString """ Augmented BaseString subclass. AugString is a BaseString, BaseString is NOT an AugString """ var _nCreated as int is shared get nCreated from var is shared """ Number of AugStrings constructed to date """ def init(value as String) base.init(value) AugString._nCreated += 1 def hiChar as char hc = c'0' for c in _str hc = if(c > hc, c, hc) return hc class Cast # Down cast and call downcasted method using cast-or-nil form def downCast(what as String, b as BaseString) is shared n = b to? AugString # cast if fail return null if n s = '"[what]" is an AugString hiChar=[n.hiChar]' else s = '"[what]" is NOT an AugString' print s # Up cast using cast-or-Exception form def upCast(what as String, b) is shared try n = b to BaseString # cast: if fail throw exception s= '"[what]" is a BaseString count=[n.count]' catch InvalidCastException s= '"[what]" is NOT a BaseString' print s class CastParseDriver def showCast is shared bs = BaseString("hello - I'm a BaseString") as0 = AugString("hi - AugString") as1 = AugString("hello - Alzo AugString") assert AugString.nCreated == 2 assert as0.hiChar =='u' assert as1.hiChar=='z' bs1 as BaseString = as1 # explicitly declared as BaseString assert bs1.count == as1.count # print bs1.ordSum # not compile cos bs1 isnt a AugString Cast.downCast('bs', bs) # fail: Not AugString Cast.downCast('bs1', bs1) # is AugString Cast.upCast('bs', bs) # is BaseString Cast.upCast('bs1', bs1) # is BaseString Cast.upCast('as1', as1) # is BaseString Cast.upCast('String S', 'string-s') # fail: not BaseString def sum(l as IEnumerable) as int is shared sum as int =0 for i in l sum += i to int return sum def showParse is shared # Simple Parsing - string split, select and join str = "Beware the Jabberwock my son The claws that scratch the teeth that bite" a = str.split(@[c' ', c':']) assert a.length == 13 print a[2] s1 = String.join('.', @[ a[2], a[10], a[12] ]) assert s1 == 'Jabberwock.teeth.bite' print s1 str = '101 103 110 122 134 139 140 155 161 177' # string stream of ints a = str.split(@[c' ', c':']) # string array of (string) ints il =[] #as List i as int for strEl in a try i = int.parse(strEl) catch #FormatException, OverflowException pass success il.add(i) print il print 'sum il = [.sum(il)]' def main is shared .showCast .showParse