new_point <- function(x, y) {
structure(list(x = x, y = y), class = "Point")
}
point1 <- new_point(1, 2)
point2 <- new_point(2, 3)
# Methods live outside the class: a new one
# works for points made before it
distance_to <- function(p1, p2) {
UseMethod("distance_to")
}
distance_to.Point <- function(p1, p2) {
sqrt((p1$x - p2$x)^2 + (p1$y - p2$y)^2)
}
# Built-in classes are extended the same way
distance_to.numeric <- function(p1, p2) {
abs(p1 - p2)
}
distance <- distance_to(point1, point2)
# distance = 1.414214
number_distance <- distance_to(2, 7)
# number_distance = 5
cat("distance =", distance, "\n")
cat("number_distance =", number_distance, "\n")