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
class Coordinate(x, y) { | |
shared Integer x; | |
shared Integer y; | |
shared actual String string => "Coordinate(``x``,``y``)"; | |
} | |
/** | |
As you can see interfaces in Ceylon can provide concrete implementation of | |
methods, unlike java but comparable to Scala traits. | |
**/ | |
interface Movable { | |
shared formal variable Coordinate position; | |
shared Coordinate moveUp() => position = Coordinate(position.x, position.y + 1); | |
shared Coordinate moveDown() => position = Coordinate(position.x, position.y - 1); | |
shared Coordinate moveLeft() => position = Coordinate(position.x - 1, position.y); | |
shared Coordinate moveRight() => position = Coordinate(position.x + 1, position.y); | |
} | |
/** | |
Here we define that our class MovableObject satisfies the interface Movable | |
We have to provide an actual position and get all the move methods for free | |
**/ | |
class MovableObject(position) satisfies Movable { | |
shared actual variable Coordinate position; | |
shared actual String string => "Object located at ``position``"; | |
} | |
/** | |
You can also provide a position when it's not passed as constructor parameter | |
**/ | |
class MovableObject2(Integer x, Integer y) satisfies Movable { | |
shared actual variable Coordinate position = Coordinate(x,y); | |
shared actual String string => "Object located at ``position``"; | |
} | |
/** | |
This demo prints the following to the console | |
Object located at Coordinate(5,10) | |
Object located at Coordinate(5,11) | |
Object located at Coordinate(4,11) | |
**/ | |
void interface_demo() { | |
MovableObject movable = MovableObject(Coordinate(5,10)); | |
print(movable); | |
movable.moveUp(); | |
print(movable); | |
movable.moveLeft(); | |
print(movable); | |
} |
No comments:
Post a Comment