Multiple inheritance for R6 classes

前端 未结 2 1711
陌清茗
陌清茗 2021-02-03 10:08

Actual question

What are my options to workaround the fact that R6 does not support multiple inheritance?

Disclaimer

I know that R is primarily a fun

2条回答
  •  礼貌的吻别
    2021-02-03 10:53

    Plus: I don't see what's wrong with mimicking OOD principles/behavior when you know you're prototyping for an object-oriented language such as C#, Java, etc.

    What’s wrong with it is that you needed to ask this question because R is simply an inadequate tool to prototype an OOD system, because it doesn’t support what you need.

    Or just prototype those aspects of your solution which rely on data analysis, and don’t prototype those aspects of the API which don’t fit into the paradigm.

    That said, the strength of R is that you can write your own object system; after all, that’s what R6 is. R6 just so happens to be inadequate for your purposes, but nothing stops you from implementing your own system. In particular, S3 already allows multiple inheritance, it just doesn’t support codified interfaces (instead, they happen ad-hoc).

    But nothing stops you from providing a wrapper function that performs this codification. For instance, you could implement a set of functions interface and class (beware name clashes though) that can be used as follows:

    interface(Printable,
        print = prototype(x, ...))
    
    interface(Comparable,
        compare_to = prototype(x, y))
    
    class(Foo,
        implements = c(Printable, Comparable),
        private = list(x = 1),
        print = function (x, ...) base::print(x$x, ...),
        compare_to = function (x, y) sign(x$x - y$x))
    

    This would then generate (for instance):

    print.Foo = function (x, ...) base::print(x$x, ...)
    
    compare_to = function (x, y) UseMethod('compare_to')
    
    compare_to.foo = function (x, y) sign(x$x - y$x)
    
    Foo = function ()
        structure(list(x = 1), class = c('Foo', 'Printable', 'Comparable'))
    

    … and so on. In fact, S4 does something similar (but badly, in my opinion).

提交回复
热议问题