https://kotlinlang.org logo
Title
r

RobinVdB

11/02/2019, 5:07 PM
Is there any way to do reflection at compile time? I want to dynamically create an interface. Use case is as follows: I have a base class (Let's call it foo) and I want to get all the subclasses of foo. Then I want to create an interface which creates a method (all with the same paramters and return type) for each and every subclass of foo
n

nfrankel

11/02/2019, 5:08 PM
annotation processors are your friend...
a

Anastasia Finogenova

11/02/2019, 5:42 PM
Just out of curiosity, what is the value you see in creating that interface dynamically but in compile time through reflection vs just creating an interface and adding those methods there? I would imagine you know all the subclasses of a particular class before compiling even
r

RobinVdB

11/02/2019, 6:03 PM
Type safety. It's still possible to add a subclass of Foo without adding it to the interface, resulting in a runtime error. (Since the methods on the interface are called trough reflection)
a

Anastasia Finogenova

11/02/2019, 7:06 PM
Ok, maybe it is justified in your use case but from the first glance I would suggest avoiding reflection and looking into generics maybe instead of creating a method with the same signature for each child class 🤔
r

RobinVdB

11/02/2019, 8:35 PM
Generics don't fix the problem since I need to do dynamic dispatch. Generics are done at compile time
a

Anastasia Finogenova

11/02/2019, 8:40 PM
Yeah, you were asking for something resolved at compile time , ok, I trust you know what you are doing 😅👌
r

RobinVdB

11/02/2019, 8:48 PM
Yeah I'm doing both. I'm using dynamic dispatch to call the functions on my interface, but I want type safety so I know at compile time that for all posible values that I can call it with the thing exists.
I'm trying to write a typesafe visitor with dynamic dispatch :") I'll show you the code once I have a prototype working
a

Anastasia Finogenova

11/02/2019, 8:50 PM
Sure, don't hesitate to share
r

RobinVdB

11/02/2019, 8:56 PM
If I can make sure that visitor always contains all the subclasses of visitable in example 1, I'm sure that Visitable#accept willl never throw the RuntimeError (RuntimeError is a custom class in my code, don't mind the second argument)
t

Timmy

11/03/2019, 1:56 PM
Have you considered using sealed classes + when expressions? Depending on your use case you might not need the full blown visitor pattern. Here is a video (I couldn't find an article on it) explaining the process:

https://youtu.be/4qLj-kSOZLQ

a

Anastasia Finogenova

11/03/2019, 8:51 PM
I was also thinking about a sealed class implementation but then figured you may be developing a library