본문 바로가기

Development/Programming

[Scala] Explicitly Typed Self References

자기 자신을 다른 Type으로 선언이 가능하다.


예시를 보자


Graph라는 클래스와


  1. abstract class Graph {
  2. type Edge
  3. type Node <: NodeIntf
  4. abstract class NodeIntf {
  5. def connectWith(node: Node): Edge
  6. }
  7. def nodes: List[Node]
  8. def edges: List[Edge]
  9. def addNode: Node
  10. }


상속을 받아 또 추상화 클래스로 만들어진 DirectedGraph가 있고 여기에서 자시히 보면 protected def newEdge(from: Node, to: Node): Edge 이렇게 구현이 되어있는데.. NodeImpl 구현부에 보면 newEdge(this, node) 보면 this라고 선언이 되어있다. 하지만 Node 타입만 받기 때문에 오류가 난다. 


  1. abstract class DirectedGraph extends Graph {
  2. type Edge <: EdgeImpl
  3. class EdgeImpl(origin: Node, dest: Node) {
  4. def from = origin
  5. def to = dest
  6. }
  7. class NodeImpl extends NodeIntf {
  8. def connectWith(node: Node): Edge = {
  9. val edge = newEdge(this, node)
  10. edges = edge :: edges
  11. edge
  12. }
  13. }
  14. protected def newNode: Node
  15. protected def newEdge(from: Node, to: Node): Edge
  16. var nodes: List[Node] = Nil
  17. var edges: List[Edge] = Nil
  18. def addNode: Node = {
  19. val node = newNode
  20. nodes = node :: nodes
  21. node
  22. }
  23. }


그래서 아래와 같이 선언을 해주는 것이다. self: Node => 이렇게 선언을 하면 문법적인 오류없이 해결이 된다.


  1. abstract class DirectedGraph extends Graph {
  2. ...
  3. class NodeImpl extends NodeIntf {
  4. self: Node =>
  5. def connectWith(node: Node): Edge = {
  6. val edge = newEdge(this, node) // now legal
  7. edges = edge :: edges
  8. edge
  9. }
  10. }
  11. ...
  12. }




'Development > Programming' 카테고리의 다른 글

[Scala] Generic function  (0) 2015.09.05
[Scala] Local Type Inference  (0) 2015.03.17
[Scala] Lower Type Bounds  (0) 2015.03.12
[Scala] Upper Type Bounds  (0) 2015.03.11
[Scala] Traits  (0) 2015.03.07