Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn kotlin Class Functions


Certainly! In Kotlin, class functions, also known as methods, are functions that are defined within a class and operate on the class's data. They encapsulate behavior related to the class and enable objects of the class to perform certain actions. Here's a simple explanation with an example:

Defining Class Functions

You can define class functions within a class by placing them inside the class body. These functions can access the properties and other functions of the class.

Example

class Calculator {
fun add(a: Int, b: Int): Int {
return a + b
}

fun subtract(a: Int, b: Int): Int {
return a - b
}

fun multiply(a: Int, b: Int): Int {
return a * b
}

fun divide(a: Int, b: Int): Double {
if (b == 0) {
throw IllegalArgumentException("Cannot divide by zero")
}
return a.toDouble() / b.toDouble()
}
}

In this example:

Using Class Functions

You can use class functions by calling them on objects of the class. Class functions are invoked using the dot notation (object.function()).

Example

fun main() {
val calc = Calculator()

val sum = calc.add(5, 3)
println("Sum: $sum") // Output: Sum: 8

val difference = calc.subtract(10, 4)
println("Difference: $difference") // Output: Difference: 6

val product = calc.multiply(6, 7)
println("Product: $product") // Output: Product: 42

val quotient = calc.divide(20, 4)
println("Quotient: $quotient") // Output: Quotient: 5.0
}

In this example:

Conclusion

Class functions in Kotlin are essential for encapsulating behavior within classes and enabling objects to perform specific actions. They provide a structured and organized way to define and use functionality related to a class. Understanding and utilizing class functions is crucial for writing object-oriented Kotlin code.

Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java