haskellaesonghc-generics

deriving Generic and ToJSON at the same time?


I have a module Foo.hs which contains a definition which does not derive Generic:

-- Foo.hs
data Blather = Blather ...  -- Generic not derived here

And in another module I want to derive ToJSON:

-- Bar.hs
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}

import GHC.Generics
import Data.Aeson

instance Generic Blather
instance ToJSON Blather

but it doesn't compile. If I derive Generic in Foo.hs at the definition site I can later derive ToJSON in another module.

Can I derive ToJSON Blather in Bar.hs without modifying the original Foo.hs?

Or is there a simple way to write instance ToJSON Blather by hand?


Solution

  • Enable StandaloneDeriving and use deriving instance ... since this doesn't require that the derivation is in the same module as the data type.

    Example:

    {-# LANGUAGE DeriveGeneric, StandaloneDeriving, DeriveAnyClass #-}
    
    import GHC.Generics
    import Data.Aeson
    import Foo
    
    deriving instance Generic Blather
    deriving instance ToJSON Blather
    
    main = undefined