Last active
August 17, 2016 18:43
-
-
Save Perelandric/a28b82e35444314de1ea4ad08aeccb51 to your computer and use it in GitHub Desktop.
Trying to make generic class with clone method
This file contains 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
actor Main | |
new create(env: Env) => | |
let foo_layers = Layers[Foo] // `Layers` of `Foo` | |
// The important part is that it defines a clone() | |
trait MyTrait[U] | |
new create() | |
fun clone(): U | |
// One of several classes that will implement MyTrait | |
class Foo is MyTrait[Foo iso^] | |
new create() => None | |
fun clone(): Foo iso^ => recover Foo end | |
// A generic type that holds an Array of the respective MyTrait types, like Foo | |
class Layers[T: MyTrait[T]] | |
var values: Array[T] = Array[T] | |
fun clone(): Layers[T] => | |
// The clone we're creating | |
let c = recover Layers[T] end | |
var i = USize(0) | |
let len = values.size() | |
// The array for the clone | |
let a = recover Array[T](len) end | |
// Clone each item in the original array to the new array | |
while i < len do | |
try | |
let item: T = values(i).clone() | |
a.push(recover ref item end) | |
end | |
i = i + 1 | |
end | |
// Put the new array of cloned items on the main clone | |
c.values = consume a | |
c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here are the highlights:
MyTrait
defines aclone()
that should ultimately return aniso^
copy of whatever is implementing the traitFoo
is a class that implementsMyTrait
Layers
is a generic class that simply wraps an Array ofT: MyTrait
The trouble is that I'm trying to give
Layers
its ownclone()
method that performs a deep clone. While theclone()
is meant to produce aniso
, it'll ultimately be placed into the Array as aref
.Note that the Array in
Layers
holdsT: MyTrait
, not simplyMyTrait
.What I show above is one of my earlier, simpler attempts, which is clearly wrong. Some guidance would be appreciated.