From hpages at fhcrc.org  Wed Apr  9 20:58:46 2008
From: hpages at fhcrc.org (Herve Pages)
Date: Wed, 09 Apr 2008 11:58:46 -0700
Subject: [Rd] coerce methods and inheritance
Message-ID: <47FD11E6.1090901@fhcrc.org>

Hi,

It doesn't seem that the dispatching algo is finding my coerce method under
some circumstances.
Let's say I have 2 classes, A and AA and that AA is just a direct extension
of A with no additional slots:

   setClass("A", representation(ii="integer"))
   setClass("AA", contains="A")

I can define a method for coercing my objects to an integer vector with:

   setAs("A", "integer", function(from) {cat("I'm the A->integer coerce method\n"); from at ii})

and this works as expected when my object is an AA instance:

   > aa <- new("AA", ii=sample(10, 5))
   > as(aa, "integer")
   I'm the A->integer coerce method
   [1] 10  1  6  4  7

But things don't behave that way anymore if I introduce a direct extension of AA:

   setClass("OrderedAA",
     contains="AA",
     validity=function(object)
     {
         if (!all(diff(object at ii) >= 0))
             return("slot 'ii' is not ordered")
         TRUE
     }
   )

and a method for coercing an A object to an OrderedAA object:

   setAs("A", "OrderedAA",
     function(from)
     {
         cat("I'm the A->OrderedAA coerce method\n")
         new("OrderedAA", ii=sort(from at ii))
     }
   )

My A->OrderedAA coerce method is not called anymore:

   > oaa <- as(aa, "OrderedAA")
   > oaa
   > validObject(oaa)
   Error in validObject(oaa) :
     invalid class "OrderedAA" object: slot 'ii' is not ordered

This looks like a bug to me.

Thanks,
H.



[Rd] coerce methods and inheritance
Herve Pages