我想要一个接受只读列表的数据类:
data class Notebook(val notes: List<String>) {
}
Run Code Online (Sandbox Code Playgroud)
但它也可以接受MutableList,因为它是一个子类型List.
例如,以下代码修改传入的列表:
fun main(args: Array<String>) {
val notes = arrayListOf("One", "Two")
val notebook = Notebook(notes)
notes.add("Three")
println(notebook) // prints: Notebook(notes=[One, Two, Three])
}
Run Code Online (Sandbox Code Playgroud)
有没有办法如何在数据类中执行传入列表的防御副本?
说我有3个perl文件.
run.pl
#!/usr/bin/perl
use strict;
use warnings;
use Common;
validate(); # no need of Common::validate()
Run Code Online (Sandbox Code Playgroud)
Common.pm
package Common;
use strict;
use warnings;
use Exporter qw(import);
use Validator;
our @EXPORT = qw(validate inArray);
sub validate
{
Validator::doSomething();
}
sub inArray
{
print("HERE\n");
}
return 1;
Run Code Online (Sandbox Code Playgroud)
Validator.pm
package Validator;
use strict;
use warnings;
use Common;
sub doSomething
{
inArray(); # only Common::inArray() works here, why?
}
return 1;
Run Code Online (Sandbox Code Playgroud)
运行时输出为: Undefined subroutine &Validator::inArray called at Validator.pm line 10.
如果我改变
sub doSomething
{
inArray(); …Run Code Online (Sandbox Code Playgroud)