-2

I'm currently learning java in order to make an app on android and I checked that swift has a structure that stores information in memory. I'd like to know, if in java this type of object exists, because the class storage the reference on the memory. Also I checked that Kotlin has a data class, does java have a similar object?

Andronicus
  • 25,419
  • 17
  • 47
  • 88
cristian_064
  • 576
  • 3
  • 16
  • What exactly do you mean when you say "structure that stores information in memory"? All objects are stored in memory in Java or Kotlin or any other language. Is there something specific about Kotlin's data classes that you want to replicate in Java? – Leo Aso Oct 19 '19 at 09:34
  • In swift, exist one type of object called structured that is of value type(A value type is a type whose value is copied when it’s assigned to a variable or constant, or when it’s passed to a function.) like primitive data, the structure also has method and property. on the other hand the Classes Are Reference Types (reference types are not copied when they are assigned to a variable or constant, or when they are passed to a function. Rather than a copy, a reference to the same existing instance is used) https://stackoverflow.com/questions/24232799/why-choose-struct-over-class – cristian_064 Oct 19 '19 at 16:15
  • so I wondered if java has something like structure.? – cristian_064 Oct 19 '19 at 16:15

3 Answers3

1

No, there is nothing like that, but there are tools, that try to mimic this behavior, for example lombok. Using @Data annotation we're getting default constructor, getters, setters, toString, equals, hashCode. We can fine-tune it by using annotations like @Getter, @NoArgsConstructor etc.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
0

Neither Java nor Kotlin have anything similar to those Swift types you are talking about. Assignment always copies references to an object, rather than the object itself. What Kotlin's data classes do is that they create a copy method (among other things) that allows you to explicitly make a copy of an object, but you still have to actually call the method.

val b = a // b and a point to the same object, even if it is a data class
val b = a.copy() // this is what you need to do to create a copy of a data class

Java assignment copies references, not objects, and the same is true for Kotlin. There is no way around this, because it is a feature of the language itself. Copy constructors and methods (like what Kotlin's data class gives you) are the closest thing you have to such a feature. To get something like this in Java without having to manually write the code everytime, you could look into Project Lombok.

Leo Aso
  • 11,898
  • 3
  • 25
  • 46
0

Starting with Java 14 you will have access to Record immutable class. It is similar in concept to data class in Kotlin.

nabster
  • 1,561
  • 2
  • 20
  • 32