How to use transient in kotlin

in #java6 years ago (edited)

What is transient in java

  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

  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.

How to use in kotlin

// 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"
}

When to use

  • Field are calculated from other fields within instance of class.
  • For secure information which should not leak outside the JVM.

Coin Marketplace

STEEM 0.28
TRX 0.12
JST 0.033
BTC 66845.00
ETH 3089.30
USDT 1.00
SBD 3.72