Therefore, now our fridge will only be able to access eatable items.
Fridge
class that will only accept types implementing the Eatable
interface:class Fridge<T: Eatable)> { public function new() {} }
add
and a remove
method and we will use an Array
to store the list of what is inside our Fridge
:class Fridge<T: Eatable)> { private var items : Array<T>; public function new() { items = new Array<T>(); //Initialize the Array } public function add(item : T) { array.push(item); } public function remove(item : T) { array.remove(item); } }
For sure, in this state, our fridge is basically just a wrapper around the array class, but now we will do something interesting with it.
Eatable
interface, so that we can store the date before which the eatable should be eaten, as follows:interface Eatable { public var eatBefore : Date; }
public function removeOldItems() { for(eatable in items) { if(eatable.eatBefore.getTime() <Date.now().getTime()) //Should've been eaten earlier { this.remove(eatable); } } }
In the preceding Time for action, we have put to practice what we have seen in this chapter about type parameters and constraints.
Fridge
class, therefore allowing us to add and remove items to and from it, still knowing that they are of a specific type (T
can represent any type extending or implementing Eatable
, or even just Eatable
). T
, we knew that all objects of this abstract type would be of type Eatable
. This allowed us to use the public
field defined in the Eatable
interface.Try to create a container for three values (we will create a class with first, second, and third fields to store these values).
These values should be typed, but the class should be able to store any type of values (these should all be of the same type).
a. One type
b. Two types
c. Three types
d. As many types as we want
a. cast (variable, NewType)
b. cast variable
c. untyped { var var2: NewType = variable;}
a. Explicitly
b. Through inference
c. Untyped
a. No constraints at all
b. One constraint at most
c. Two constraints at most
d. An unlimited number of constraints
a. True
b. False
18.218.31.165