Companion functions and interfaces

Interfaces can be implemented by companion objects as well as by normal and object classesLet's take a look at how this can be done:

  1. Create an Employee class with two properties, name and id, and an interface, EmployeeInterface, with add in the function signature:
data class Employee(val name: String, val id: Int)

interface EmployeeInterface{
fun create(name: String, id: Int) : Employee
}

class EmployeeFactory {

companion object : EmployeeInterface{

override fun add(name:String, id: Int): Employee {
return Employee(name,id)
}
}
}

This function takes two variables and returns the Employee object.

  1. Create a class, EmployeeFactory, and implement the interface in the companion object. Provide the implementation of the add function, which is declared in EmployeeInterface:
fun main(args: Array<String>) {
val emp1 = EmployeeFactory.add("Abid",1);
val emp2 = EmployeeFactory.add("Igor",2);

println(emp1)
println(emp2)
}

We can now call the add function from the companion object using the EmployeeFactory class and get the employee object successfully. Verify this by printing each object on the screen. The output will be as follows:

Employee(name= Abid, id=1)
Employee(name= Igor, id=2)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.183.210