Last active
August 29, 2015 14:01
-
-
Save joshbode/ff4e306991c0d092b682 to your computer and use it in GitHub Desktop.
Nullable Reference Class fields in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #' 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