Difference Between Return Types and Class Extends

Hi All,

I am an fresher to Kotlin and getting hands on to it with prior experience of being in Java for around 8+ Years, One thing which looks different for me is on how Kotlin differentiates between return types and extends keyword (":"). Here is one such example

'> **fun getMyData(): LiveData<List<MyDataModel>>**'

In the above quote we say getMyData() will return List of MyDataModel class

Similarly when we define any Android activity or fragments we will use it in this way

> **class MyFragment : Fragment()**

In the above statement we are saying our class will extend Fragment.

Kindly clarify me why Kotlin uses same notation for extending and also for return types? Is there any advantages for the same depiction

Thanks
Venkatraman K G

I don’t think the reason for this is similarity. Based on what I can tell it’s just a result of how the language developed. I’m not part of the kotlin team so all this is speculation, but the syntax for inheritance is lifted from languages like C++, C# (just to mention 2 big ones). I personally prefer it to java’s extends and implements keyword. And differentiating between interface and class in inheritance is no problem because inheriting form classes requries a constructor call.

class Foo: Bar

vs

class Foo: Bar()

The return type of functions is a bit harder to explain. My guess is that they wanted it to be consistent with property declarations eg. name before type.

val foo: Int
fun bar(): Int

This is probably done because type inference allows kotlin to skip the type for properties (and single expression functions). Adding the type after the name just feels more natrual, especially since it needs a keyword at the beginning anyways (this is again necessary because of properties/functions with infered type). No keyword isn’t an option or it would no longer be possible to differentiate between declaration and usage of a property/function.

Having the return type after the function arguments is lifted from Pascal. The same as for variable type syntax.

Also I always think of the : as something like an “is a” relation.

When extending with A : B, then values of type A are also of type B. When declaring a function fun a(): B, then values returned by this function are also of type B. In both cases we have an “is a” relation.

Thanks for your reply!!

Thanks for clear explanation!! :grinning: