1

I use scala with mybatis:

Space.scala:

case class Space(
              val id: Long ,
              spaceName:String)

SpaceDao:

   val space=Space(0,"space name")
   val mapper = session.getMapper(classOf[SpaceMapper])
   val result = mapper.insertSpace(space)
   println(space.id)

The result space id is the auto increment number of mysql, not 0. but both space and space.id is val, why a val value can be changed?

Paul Wang
  • 83
  • 4
  • how can you prove that `space` id has changed? – ka4eli Sep 22 '15 at 02:27
  • I tracked the code when running a inserting, it's same object but the `id` value is change by mybatis in class SetFieldInvoker, after "field.set(target, args[0])", the field is "private final long model.Space.id" – Paul Wang Sep 22 '15 at 02:45
  • 1
    possible duplicate of [Scala Reflection to update a case class val](http://stackoverflow.com/questions/21431263/scala-reflection-to-update-a-case-class-val) – Dimitris Fasarakis Hilliard Sep 22 '15 at 03:00

1 Answers1

3

This can be achieved via reflection(which is used by SetFieldInvoker):

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.

Also see this question.

Community
  • 1
  • 1
ka4eli
  • 5,294
  • 3
  • 23
  • 43