transient is a key-word. Transient in java is used to on class variable to indicate that serialization process of such class should ignore such variables. A Transient variable is a variable that can not be serialized.
Variables may be marked transient to indicate that they are not part of the persistent state of an object. __java official doc
transient in kotlin is replaced by @Transient.
@Target([AnnotationTarget.FIELD]) annotation class Transient
Marks the JVM backing field of the annotated property as transient, meaning that it is not part of the default serialized form of the object.
// create serializable object
class Rectangle : Serializable {
var length: Int = 0
var width: Int = 0
@Transient var area: Int? = null
//calculate rectangle area
fun calcArea() {
area = length * width
}
}
fun main(args: Array<String>) {
val rec = Rectangle()
rec.length = 3
rec.width = 4
rec.calcArea()
println("area :${rec.area}") // "area :12"
//serialize rectangle
val recName = "rec.txt"
val oos = ObjectOutputStream(FileOutputStream(recName))
oos.writeObject(rec)
oos.flush()
oos.close()
//de-serialize rectangle
val ois = ObjectInputStream(FileInputStream(recName))
val deRec = ois.readObject() as Rectangle
ois.close()
println("de-Rec area:" + deRec.area) // "de-Rec area:null"
}