Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to remove a Trait from an instance in Scala?

Tags:

scala

traits

I would like to know if having an instance to which a trait has been added to in runtime, it is possible to remove the trait off the instance, so it can behave as originally.

like image 606
Pedro Rolo Avatar asked Feb 24 '23 05:02

Pedro Rolo


1 Answers

Traits are combined with classes at compile-time. So it is not possible to add/remove traits at run-time.

For your particular case, consider adding a method to your class:

class Foo(val a: Object, val b: Object, ...) {
  def original() = new Foo(a, b, ...)
}

Then you can call instance.original() to get back a copy of your object that is not affected by any traits.

like image 52
Lex Avatar answered Feb 25 '23 23:02

Lex