Skip to content

Instantly share code, notes, and snippets.

@joshbode
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save joshbode/ff4e306991c0d092b682 to your computer and use it in GitHub Desktop.

Select an option

Save joshbode/ff4e306991c0d092b682 to your computer and use it in GitHub Desktop.
Nullable Reference Class fields in R
#' Create a nullable class field for a reference class.
#'
#' @param name name of class.
#' @examples \dontrun{
#' Foo = setRefClass('Foo', fields=c(a=nullable('list'), b='character'))
#' x = Foo$new(a=list(1,2,3), y="Non-NULL 'a'")
#' y = Foo$new(a=NULL, y="NULL 'a'")
#' }
nullable = function(name) {
union_name = paste(name, 'NULL', sep='_')
tryCatch({
# use cached definition
getClass(union_name)
},
error=function(e) {
# register new definition
setClassUnion(union_name , c(name, 'NULL'))
})
return(union_name)
}
condition = setRefClass('condition',
fields=list(call=nullable('call'), traceback='list', message='character'),
methods=list(
initialize=function(call=NULL, traceback=list(), message='') {
.self$call = call
.self$traceback = traceback
.self$message = message
return(.self)
}
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment