Wiki

Changes between Version 12 and Version 13 of MixIn

Show
Ignore:
Timestamp:
07/29/13 11:50:07 (11 years ago)
Author:
hopscc
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • MixIn

    v12 v13  
    33== Introduction == 
    44 
    5 To be done. In the mean time, see the [http://cobra-language.com/forums/viewtopic.php?f=4&t=306 discussion thread]. 
     5Provide a non inheritance based capability for shared/common behaviour. 
     6 
     7Basically, selected traits or behaviours are described in a special Type called a 'mixin' (analogous to an interface),[[BR]] 
     8these can then be specified on a class and are injected into that class to provide those behaviours on that class.   
     9 
     10 
     11Mixin behaviours can be specified using object: 
     12  * vars 
     13  * properties 
     14  * methods 
     15They do not support constructors 
     16 
     17(For more see the [http://cobra-language.com/forums/viewtopic.php?f=4&t=306 Forum discussion thread]). 
    618 
    719== Compared to Extensions == 
     
    1426 * Mixins cannot be used from a [wiki:BinaryLibrary binary library]. The source must be included for the compiler. 
    1527 
    16 In summary, mixins are more about multiple inheritance among the types you are declaring. Extensions are about adding convenience methods to existing types (regardless of who declared them). 
     28In summary, mixins are more about implementing shared capabilities among the types you are declaring. [[BR]] 
     29Extensions are about adding convenience methods to existing types (regardless of who declared them). 
    1730 
    1831== Restrictions == 
     
    2841 * Two or more mixins added to a single type cannot have collision in their member names. 
    2942 
     43== Example == 
     44{{{ 
     45#!cobra 
     46 
     47# The behaviour desired - a name property 
     48mixin Named 
     49    var _name as String? 
     50    pro name as String 
     51        get 
     52            return _name ? '' 
     53        set 
     54            _name = value 
     55 
     56   get capName 
     57        return _name[:1].toUpper + _name[1:] 
     58         
     59         
     60# the (otherwise empty) class with mixin added 
     61class A adds Named       
     62    pass 
     63 
     64def main is shared 
     65    a = A() 
     66    assert a inherits Named 
     67    assert a.name == '' 
     68    a.name = 'arosebyanyothername' 
     69    assert a.name == 'arosebyanyothername' 
     70    assert a.capName == 'Arosebyanyothername' 
     71}}} 
     72 
    3073== See also == 
    3174