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.

4
  • So make it mutable, but only within the class, so you can change it. Commented Nov 11, 2012 at 1:42
  • I really need to return a new instance of Hidable. Commented Nov 11, 2012 at 1: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: stackoverflow.com/questions/10373318/… Commented Nov 11, 2012 at 1:54
  • Better copy paste my function everywhere then :d Commented Nov 11, 2012 at 2:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I use the latest scalaz, and if it's to add manually a Lense for a single field, I better cp: copy :(
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: gist.github.com/1404336#file_lens.scala, the new way: github.com/folone/poi.scala/blob/master/src/main/scala/info/…. Or create a plugin of your own, using macros.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.