2

I'm making a strategic game and I try to apply what I learned, try to use immutable data. In my game I have Units, these units can have different special function. By exemple some plane can hide themselves. What I search is a way to be able to do some sort of

abstract class Units {
val life:Int
}

trait Hidable { self: Units => 
val hided:Boolean
def hide:Units with Hidable= ....
}

without having to copy paste:

def hide = copy(hided=true)

on every case class that mixin Hidable.

Atol
  • 569
  • 4
  • 12
  • So make it mutable, but only within the class, so you can change it. – James Black Nov 11 '12 at 01:42
  • I really need to return a new instance of Hidable. – Atol Nov 11 '12 at 01:44
  • 1
    Only metaprogramming with macros or toolboxes can help you, since the `copy` method of each case class is generated by compiler. You can learn more about it here: http://stackoverflow.com/questions/10373318/mixing-in-a-trait-dynamically – Nikita Volkov Nov 11 '12 at 01:54
  • Better copy paste my function everywhere then :d – Atol Nov 11 '12 at 02:14

1 Answers1

1

A common way to update an immutable data structure -- is using lenses. There's a compiler plugin to generate lenses for your code, though it is not very production-ready. It is also available for an old scalaz only.

Here's a related question.

Community
  • 1
  • 1
George
  • 8,368
  • 12
  • 65
  • 106
  • I use the latest scalaz, and if it's to add manually a Lense for a single field, I better cp: copy :( – Atol Nov 11 '12 at 11:39
  • If you are to modify a single field, you'll get by with a `copy`. If at some point you end up updating a deeply nested structure, lenses are a way to go. You can modify that compiler plugin to generate lenses in a way, scalaz-seven specifies. The difference isn't than big: the old way: https://gist.github.com/1404336#file_lens.scala, the new way: https://github.com/folone/poi.scala/blob/master/src/main/scala/info/folone/scala/poi/package.scala#L49. Or create a plugin of your own, using macros. – George Nov 11 '12 at 15:13