Post

Property vs Function in Kotlin

Property vs Function in Kotlin

Definition

Property: A property is a characteristic or attribute of an object that holds data. It represents a state or value that belongs to a class or object.

Function: A function is a block of code that performs a specific task or action. It represents behavior and can optionally return a value.

Key Differences

AspectPropertyFunction
PurposeStores data/statePerforms action/computation
SyntaxNo parentheses ()Requires parentheses ()
AccessDirect access like a fieldCalled/invoked with ()
Naming ConventionNoun (what it is)Verb (what it does)
Can have parametersNoYes
Typical useGet or set valuesExecute logic or calculations

Property in Kotlin

Properties represent the state of an object. They can have getters and setters.

Syntax

1
2
3
4
5
// Read-only property (val)
val propertyName: Type = initialValue

// Mutable property (var)
var propertyName: Type = initialValue

Examples

1
2
3
4
5
6
7
8
9
class Person {
    val name: String = "Arjun"  // Read-only property
    var age: Int = 25           // Mutable property
}

val person = Person()
println(person.name)  // Access property (no parentheses)
println(person.age)   // Access property (no parentheses)
person.age = 26       // Modify property

Custom Getters and Setters

Properties can have custom logic:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Rectangle(val width: Int, val height: Int) {
    // Property with custom getter
    val area: Int
        get() = width * height
    
    // Property with custom getter and setter
    var displayName: String = ""
        get() = field.uppercase()
        set(value) {
            field = if (value.isNotEmpty()) value else "Unknown"
        }
}

val rect = Rectangle(5, 10)
println(rect.area)  // 50 (computed each time)

Function in Kotlin

Functions represent behavior or actions that an object can perform.

Syntax

1
2
3
4
fun functionName(parameter: Type): ReturnType {
    // function body
    return value
}

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Calculator {
    // Function with parameters and return value
    fun add(a: Int, b: Int): Int {
        return a + b
    }
    
    // Function without parameters
    fun printMessage(): Unit {
        println("Hello from Calculator")
    }
}

val calc = Calculator()
val result = calc.add(5, 3)  // Call function with parentheses
calc.printMessage()          // Call function with parentheses

How to Identify: Property or Function?

Look at the Syntax

1
2
3
4
5
6
7
8
9
10
11
12
val numbers = arrayOf(1, 2, 3, 4, 5)

// Property - no parentheses
numbers.size          // Property
numbers.indices       // Property
numbers.lastIndex     // Property

// Function - has parentheses
numbers.isEmpty()     // Function
numbers.first()       // Function
numbers.sum()         // Function
numbers.contains(3)   // Function

Naming Convention

1
2
3
4
5
6
7
8
9
10
11
// Properties (nouns - what it is)
person.name
person.age
rectangle.width
array.size

// Functions (verbs - what it does)
person.getName()      // Gets name
person.updateAge()    // Updates age
rectangle.calculateArea()  // Calculates area
array.isEmpty()       // Checks if empty

When to Use Property vs Function

Use Property When:

  1. Representing state or characteristic
1
2
3
4
class Car {
    val brand: String = "Toyota"
    var speed: Int = 0
}
  1. Simple computation without parameters
1
2
3
4
class Circle(val radius: Double) {
    val area: Double
        get() = Math.PI * radius * radius
}
  1. Accessing or storing data
1
2
val text = "Hello"
println(text.length)  // Property: characteristics of the string

Use Function When:

  1. Performing an action or operation
1
2
3
4
5
class Printer {
    fun printDocument(doc: String) {
        println(doc)
    }
}
  1. Computation requires parameters
1
2
3
4
5
class Math {
    fun power(base: Int, exponent: Int): Int {
        return base.toDouble().pow(exponent.toDouble()).toInt()
    }
}
  1. Complex logic or side effects
1
2
3
4
5
6
class Database {
    fun saveData(data: String) {
        // Complex logic to save data
        println("Saving: $data")
    }
}
  1. Name implies action
1
2
3
4
val numbers = arrayOf(5, 2, 8, 1)
numbers.sort()           // Action: sort the array
numbers.reverse()        // Action: reverse the array
println(numbers.max())   // Action: find maximum

Real-World Analogy

Think of a Car:

Properties (characteristics):

  • color - what color is the car
  • speed - how fast it’s going
  • fuelLevel - how much fuel it has

Functions (actions):

  • start() - start the engine
  • accelerate(amount) - increase speed
  • brake() - slow down
  • refuel(liters) - add fuel
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Car {
    // Properties - state
    var color: String = "Red"
    var speed: Int = 0
    var fuelLevel: Double = 50.0
    
    // Functions - behavior
    fun start() {
        println("Engine started")
    }
    
    fun accelerate(amount: Int) {
        speed += amount
        fuelLevel -= 0.5
    }
    
    fun brake() {
        speed = 0
    }
}

val myCar = Car()
println(myCar.color)    // Access property
println(myCar.speed)    // Access property
myCar.start()           // Call function
myCar.accelerate(20)    // Call function with parameter

Special Case: Functions that Look Like Properties

Some functions in Kotlin don’t require parentheses when they take no parameters, but this is rare and not recommended:

1
2
3
4
5
6
7
8
// Not common in Kotlin
fun getMessage() = "Hello"

// Can be called without parentheses (not recommended)
// val msg = getMessage

// Should be called with parentheses
val msg = getMessage()

Best Practice: Always use parentheses when calling functions for clarity.

Summary

  1. Properties store data and represent state (nouns) - accessed without parentheses.
  2. Functions perform actions and represent behavior (verbs) - called with parentheses.
  3. Properties can have custom getters/setters but no parameters.
  4. Functions can accept parameters and perform complex logic.
  5. Use properties for characteristics, functions for actions.

References

This post is licensed under CC BY 4.0 by the author.