0

Question: Does a dependable Scala library exist that provides ability to decorate a class dynamically at runtime object creation? (This is a personal learning exercise)

To be more detailed, I've explored this issue in several ways. I am aware this can be done (to some degree) using macros in Scala but I believe the compiler would have to build vast trees of the combinations involved and I'm not sure that fits the concept of truly dynamic at runtime. I've also found code snippets that use scala runtime reflection, but the authors note instability.

I have ideas of how to do this myself using TypeTags and I think it would be a great learning exercise, but many issues arise that are of course compiler related that I would be juggling:

  • dependencies
  • variance
  • illogical combinations or circular logic
  • hierarchies
  • container types

If this idea is better suited for another programming language, or abandoned in Scala I would certainly be interested to hear what other programming languages work well. (Comments appreciated) Thanks for your time.

class Animal(val name:String) 

class Dog(name:String) extends Animal(name)

trait Talks extends Animal {
  def speak():Unit ="Hello from "

}

trait Counts {
  def counts(x:Int):Unit = for (i <- 0 to x) println(x)

}

trait Walks {
  def walk():Double = 22/7
}



object RuntimeTraits extends App {

  def randomAnimal():Animal = ??? /* 
    in theory this would return a Dog, or Animal that has some (or none) of traits
    Talks, Counts, Walks, etc.  .. ref Dr.Moreau ;)
  */

}
LaloInDublin
  • 5,379
  • 4
  • 22
  • 26
  • 1
    The simple answer is "no". But what's your use-case? – The Archetypal Paul Mar 31 '16 at 15:39
  • @TheArchetypalPaul Thanks. Well some of my projects explore NP problem solving , creating dynamic solutions and such but I've also considered the idea for more practical problems like factory methods. Example: based on a string (to parse) construct an object of mixed abilities. I'm curious if languages exist that support these concepts a little cleaner – LaloInDublin Mar 31 '16 at 17:00
  • Possible duplicate of [Dynamic mixin in Scala - is it possible?](http://stackoverflow.com/questions/3254232/dynamic-mixin-in-scala-is-it-possible) – Meiko Rachimow Mar 31 '16 at 20:43

0 Answers0