Write a Kotlin Program to Add Two Complex Numbers by Passing Class to a Function

In Kotlin, we can add two complex numbers by creating a class for the complex numbers and passing an instance of that class to a function.

A complex number is a number that has both a real and imaginary component.

First, we need to create a class for the complex number. The class will have two properties: a real number and an imaginary number.

We will also define a function to add two complex numbers.

class ComplexNumber(val real: Double, val imaginary: Double) {
    fun add(other: ComplexNumber): ComplexNumber {
        return ComplexNumber(real + other.real, imaginary + other.imaginary)
    }
}

In the above code, we have defined a class called ComplexNumber.

The class has two properties: real and imaginary. We have also defined a function called add that takes another complex number as an argument and returns the sum of the two complex numbers.

Now we can use this class to add two complex numbers. Here is an example:

fun main() {
    val num1 = ComplexNumber(2.0, 3.0)
    val num2 = ComplexNumber(4.0, 5.0)
    val sum = num1.add(num2)
    println("Sum: ${sum.real} + ${sum.imaginary}i")
}

In the above code, we have created two instances of the ComplexNumber class: num1 and num2.

We then call the add function on num1 and pass num2 as an argument. The result is stored in the sum variable, and we print the result.

The output of the above code will be:

Sum: 6.0 + 8.0i

In conclusion, Kotlin provides an easy way to add two complex numbers by creating a class for the complex number and defining a function to add two complex numbers.

We can then create instances of the class and call the add function to add the complex numbers.