Created
April 6, 2019 11:33
-
-
Save chainsawriot/10be272fb369ee71dce10a54a3c8bff0 to your computer and use it in GitHub Desktop.
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
require(R6) | |
dog <- list(name = 'hundno', say = 'whhooo!') | |
class(dog) <- "animal" | |
cat <- list(name = 'kitty', say = 'meow!') | |
class(cat) <- "animal" | |
ipad <- list(name = "iPad mini") | |
class(ipad) <- "computer" | |
make_sound <- function(x, ...) { | |
UseMethod("make_sound", x) | |
} | |
make_sound.animal <- function(x, ...) { | |
print(x$say) | |
} | |
make_sound.animal <- function(x, ...) { | |
print(x$say) | |
} | |
make_sound.computer <- function(x, ...) { | |
print("...") | |
} | |
make_sound(cat) | |
make_sound(dog) | |
make_sound(ipad) | |
### The same thing in R6 | |
animal_generator <- R6::R6Class( | |
"animal", | |
private = list( | |
.dna = NULL | |
), | |
public = list( | |
name = NULL, | |
say = NULL, | |
initialize = function(name, say) { | |
self$name <- name | |
self$say <- say | |
private$.dna <- paste0(sample(c("A", "T", "G", "C"), 20, replace = TRUE), collapse = "") | |
}, | |
make_sound = function() { | |
print(self$say) | |
} | |
), | |
active = list( | |
dna = function(field) { | |
if (missing(field)) { | |
private$.dna | |
} else { | |
stop("You can't modify the info.") | |
} | |
}) | |
) | |
computer_generator <- R6::R6Class( | |
"computer", | |
public = list( | |
name = NULL, | |
initialize = function(name) { | |
self$name <- name | |
}, | |
make_sound = function() { | |
print("...") | |
} | |
) | |
) | |
dog <- animal_generator$new('hundno', 'whoooo!') | |
cat <- animal_generator$new('kitty', 'meow!') | |
dog$make_sound() | |
cat$make_sound() | |
### Active binding | |
dog$dna | |
dog$dna <- "I am modifying your DNA!" | |
### | |
ipad <- computer_generator$new('ipad') | |
ipad$make_sound() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment