TheBulgarianWolf

Kotlin Getters And Setters

Apr 3rd, 2021
595
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. fun main(args: Array<String>){
  2.     val p = Personn()
  3.     p.name = "Jack"
  4.     println("${p.name}")
  5.     val Maria = Girl()
  6.     Maria.actualAge = 15
  7.     Maria.age = 15
  8.     println("Maria: Actual age = ${Maria.actualAge}")
  9.     println("Maria: Pretended age = ${Maria.age}")
  10.  
  11.     val Marina = Girl()
  12.     Marina.actualAge = 35
  13.     Marina.age = 35
  14.     println("Marina: Actual age = ${Marina.actualAge}")
  15.     println("Marina: Pretended age = ${Marina.age}")
  16. }
  17.  
  18. class Personn{
  19.     var name: String = "defaultValue"
  20.  
  21.     get() = field
  22.  
  23.     set(value){
  24.         field = value
  25.     }
  26. }
  27.  
  28. class Girl{
  29.     var age: Int = 0
  30.     get() = field
  31.     set(value){
  32.         field = if(value < 18)
  33.             18
  34.         else if(value >= 18 && value <= 30)
  35.             value
  36.         else
  37.             value-3
  38.     }
  39.     var actualAge: Int = 0
  40. }
RAW Paste Data