Advertisement
GamesMaxed

kotlin-reflect

Nov 2nd, 2019
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.33 KB | None | 0 0
  1. // this should be generated by walking of the child classes of visitable
  2. interface Visitor {
  3.     visitExpression(expression: Expression)
  4.     visitStatement(statement: Statement)
  5. }
  6.  
  7. abstract class Visitable {
  8.     fun accept(visitor: Visitor) {
  9.         // name of the visit function
  10.         val thisKClass = this.javaClass.kotlin
  11.         val name = thisKClass.simpleName
  12.         val functionName = "visit$name"
  13.  
  14.         // find the function on the visitor
  15.         val vKClass = visitor.javaClass.kotlin
  16.         val functions = vKClass.memberFunctions
  17.         val function = functions.find { it.name == functionName } ?: throw RuntimeError("Could not find visit function called '$functionName' on visitor", null)
  18.         function.call(visitor, this)
  19.     }
  20. }
  21.  
  22. class Expression : Visitable()
  23. class Statement : Visitable()
  24.  
  25.  
  26. // Another option would be:
  27.  
  28. // this should be generated by walking of the child classes of visitable
  29. interface Visitor {
  30.     visitExpression(expression: Expression)
  31.     visitStatement(statement: Statement)
  32. }
  33.  
  34. interface Visitable {
  35.     fun accept(visitor: Visitor)
  36. }
  37.  
  38. class Expression : Visitable() {
  39.     fun accept(visitor: Visitor) {
  40.         visitor.visitExpression(this)
  41.     }
  42. }
  43. class Statement : Visitable() {
  44.     fun accept(visitor: Visitor) {
  45.         visitor.visitStatement(this)
  46.     }
  47. }
  48.  
  49. // But where is the fun in that :)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement