【发布时间】:2020-07-16 08:45:26
【问题描述】:
给定一个 R6 类 Class1 及其 initialize 函数,我希望能够传递同一类的实例并直接返回它。
类似这样的:
if("Class1" %in% class(x)) x
else Class1$new(x)
但是在 R6 类的 initialize 函数中,它应该像这样工作
# This script does not work
# Definition of the class
Class1 = R6::R6Class("Class1",
public=list(
initialize = function(x){
# This line does not work
if("Class1"%in%class(x)) return(x)
}
))
# Initiate an instance from scratch
foo = Class1$new()
# Initiate an instance through another instance
bar = Class1$new(foo)
# The two should be the same
identical(foo, bar)
#> TRUE
【问题讨论】: