Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Differentiate between kotlin's class inheritence(extends in java) and interface implementation(implements in ) here kotlin uses ( : ) for both?

Tags:

java

kotlin

As I'm working in the middle of some kotlin project I got a confusion like whether a child class implements another parent class or else implementing an interface? like I am using some interfaces and classes from a jar which I am not aware a lot about it could someone explain to me a way to solve this since I am new to kotlin.
For Example:
a class definition

abstract class Employee (val firstName: String, val lastName: String) {
    abstract fun earnings(): Double
}

which is extended by some other class

abstract class Employee (val firstName: String, val lastName: String) {
    // ... 

    fun fullName(): String {
        return lastName + " " + firstName;
    }
}

Similarly an Interface

class Result
class Student 

interface StudentRepository {
    fun getById(id: Long): Student
    fun getResultsById(id: Long): List<Result>
}

Interface implementation

class StudentLocalDataSource : StudentRepository {
    override fun getResults(id: Long): List<Result> {
       // do implementation
    }

    override fun getById(id: Long): Student {
        // do implementation
    }
}
like image 274
Purushoth.Kesav Avatar asked Dec 08 '22 14:12

Purushoth.Kesav


2 Answers

In Kotlin, to inherit from a class you have to write its primary constructor, so you will always see the parent class followed by (), sometimes with things inside.

Interfaces don't need this. You just write the names of the interfaces and that's it.

So if you see brackets after a name, that's a parent class. Otherwise its an interface.

like image 167
Sweeper Avatar answered Dec 11 '22 11:12

Sweeper


Consider the following example:

abstract class Employee(val firstName: String, val lastName: String) {
    abstract fun earnings(): Double
}

interface Hireable {
    fun hire()
}

class HireableEmployee(firstName: String, lastName: String) : Employee(firstName, lastName), Hireable {
    override fun earnings(): Double {
        return 10000.0
    }

    override fun hire() {
        //...
    }
}

as you can see the parent class is declared with a constructor invocation Employee(firstName, lastName), the interface declaration Hireable has no parentheses behind it.

So in Kotlin extends corresponds to the () behind the name signalling that this is a constructor invocation and therefore the parent class. implements has no special syntax, just the name.

For more Information about interfaces see https://kotlinlang.org/docs/reference/interfaces.html

About class hierarchies see https://kotlinlang.org/docs/reference/classes.html

like image 43
leonardkraemer Avatar answered Dec 11 '22 12:12

leonardkraemer