Open fun in kotlin

Open keyword in Kotlin

I am Amit Shekhar, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

Before we start, I would like to mention that, I have released a video playlist to help you crack the Android Interview: Check out Android Interview Questions and Answers.

In this blog, we will learn about the open keyword in Kotlin.

In Kotlin, we can mark a class , a function , or a variable with the open keyword like below:

open val slotsAvailable = 5 

Let’s understand why we use the open keyword in Kotlin.

open keyword with class

The open keyword with the class means the class is open for the extension meaning that we can create a subclass of that open class.

In Kotlin, all the classes are final by default meaning that they can not be inherited.

Suppose we have a class Mentor :

We will not be able to create a subclass of the class.

class ExperiencedMentor: Mentor()   > 

The compiler will show an error.

This type is final, so it cannot be inherited from 

If we want to allow inheritance, we need to mark the class with the open keyword. Basically, opening it for the extension.

Now, we will be able to create a subclass of this class.

class ExperiencedMentor: Mentor()   > 

You must have noticed that it is completely opposite to what we do in Java.

Let’s see how it is different in Kotlin and Java.

In Java In Kotlin
final class Mentor -> class Mentor
class Mentor -> open class Mentor

Basically, in Kotlin, all the classes are final by default but in Java, this is exactly the opposite. In Java, to make the class final, we need to use the final keyword.

That is why we need the open keyword in Kotlin with the class to allow inheritance.

open keyword with function

Similar to the classes, all the functions in Kotlin are by default final meaning that you can’t override a function.

Consider a function guide() inside the Mentor class:

open class Mentor   fun guide()   >  > 

We will not be able to override the function.

class ExperiencedMentor : Mentor()   override fun guide()   >  > 

The compiler will show an error.

guide' in 'Mentor' is final and cannot be overridden 

In order to allow the overriding of the function, we need to add the open keyword.

open class Mentor   open fun guide()   >  > 

We will be able to override the function now like below:

class ExperiencedMentor : Mentor()   override fun guide()   >  > 

Again, in Kotlin, all the functions are final by default but in Java, this is exactly the opposite. In Java, to make the function final, we need to use the final keyword.

That is why we need the open keyword in Kotlin with the function to allow it to be overridden.

open keyword with variable

Similarly, the variables in Kotlin are final by default. So, to override it in the child class, we need to set the variables as open in our base class.

Here is the base class Mentor :

open class Mentor   val slotsAvailable = 5  > 
class ExperiencedMentor : Mentor()   override val slotsAvailable = 10  > 

We will not be able to override the variable.

The compiler will show an error.

'slotsAvailable' in 'Mentor' is final and cannot be overridden 

In order to allow the overriding of the variable, we need to add the open keyword.

open class Mentor   open val slotsAvailable = 5  > 

We will be able to override the variable now like below:

class ExperiencedMentor : Mentor()   override val slotsAvailable = 10  > 

Again, in Kotlin, all the variables are final by default but in Java, this is exactly the opposite. In Java, to make the variable final, we need to use the final keyword.

That is why we need the open keyword in Kotlin with the variable to allow it to be overridden.

So, now we must have understood the open keyword in Kotlin.

Master Kotlin Coroutines from here: Mastering Kotlin Coroutines

You can connect with me on:

Источник

Inheritance

All classes in Kotlin have a common superclass, Any , which is the default superclass for a class with no supertypes declared:

Any has three methods: equals() , hashCode() , and toString() . Thus, these methods are defined for all Kotlin classes.

By default, Kotlin classes are final – they can’t be inherited. To make a class inheritable, mark it with the open keyword:

To declare an explicit supertype, place the type after a colon in the class header:

If the derived class has a primary constructor, the base class can (and must) be initialized in that primary constructor according to its parameters.

If the derived class has no primary constructor, then each secondary constructor has to initialize the base type using the super keyword or it has to delegate to another constructor which does. Note that in this case different secondary constructors can call different constructors of the base type:

Overriding methods

Kotlin requires explicit modifiers for overridable members and overrides:

The override modifier is required for Circle.draw() . If it’s missing, the compiler will complain. If there is no open modifier on a function, like Shape.fill() , declaring a method with the same signature in a subclass is not allowed, either with override or without it. The open modifier has no effect when added to members of a final class – a class without an open modifier.

A member marked override is itself open, so it may be overridden in subclasses. If you want to prohibit re-overriding, use final :

Overriding properties

The overriding mechanism works on properties in the same way that it does on methods. Properties declared on a superclass that are then redeclared on a derived class must be prefaced with override , and they must have a compatible type. Each declared property can be overridden by a property with an initializer or by a property with a get method:

You can also override a val property with a var property, but not vice versa. This is allowed because a val property essentially declares a get method, and overriding it as a var additionally declares a set method in the derived class.

Note that you can use the override keyword as part of the property declaration in a primary constructor:

interface Shape < val vertexCount: Int >class Rectangle(override val vertexCount: Int = 4) : Shape // Always has 4 vertices class Polygon : Shape < override var vertexCount: Int = 0 // Can be set to any number later >

Derived class initialization order

During the construction of a new instance of a derived class, the base class initialization is done as the first step (preceded only by evaluation of the arguments for the base class constructor), which means that it happens before the initialization logic of the derived class is run.

This means that when the base class constructor is executed, the properties declared or overridden in the derived class have not yet been initialized. Using any of those properties in the base class initialization logic (either directly or indirectly through another overridden open member implementation) may lead to incorrect behavior or a runtime failure. When designing a base class, you should therefore avoid using open members in the constructors, property initializers, or init blocks.

Calling the superclass implementation

Code in a derived class can call its superclass functions and property accessor implementations using the super keyword:

open class Rectangle < open fun draw() < println("Drawing a rectangle") >val borderColor: String get() = «black» > class FilledRectangle : Rectangle() < override fun draw() < super.draw() println("Filling the rectangle") >val fillColor: String get() = super.borderColor >

Inside an inner class, accessing the superclass of the outer class is done using the super keyword qualified with the outer class name: super@Outer :

Overriding rules

In Kotlin, implementation inheritance is regulated by the following rule: if a class inherits multiple implementations of the same member from its immediate superclasses, it must override this member and provide its own implementation (perhaps, using one of the inherited ones).

To denote the supertype from which the inherited implementation is taken, use super qualified by the supertype name in angle brackets, such as super :

open class Rectangle < open fun draw() < /* . */ >> interface Polygon < fun draw() < /* . */ >// interface members are ‘open’ by default > class Square() : Rectangle(), Polygon < // The compiler requires draw() to be overridden: override fun draw() < super.draw() // call to Rectangle.draw() super.draw() // call to Polygon.draw() > >

It’s fine to inherit from both Rectangle and Polygon , but both of them have their implementations of draw() , so you need to override draw() in Square and provide a separate implementation for it to eliminate the ambiguity.

Источник

open Keyword in Kotlin

Keywords are some predefined or specific reserved words in programming languages each of which has a specific feature associated with it. Almost all of the words which help us use the functionality of the programming languages are included in the list of keywords. So you can imagine that the list of keywords is not going to be a small one, and the “open” keyword is also one of them, so this article is also based on open keyword. Now let’s try to understand the “open” keyword in kotlin. As we all know that kotlin is a modern and highly recommended language for android app development. because it really makes android app development easier a lot, and we all should know that it is also the modification of the java programming language, so why not we understand the “open” keyword by comparison with java. i.e what we can use instead of “open” keyword in java. So basically java has a keyword named “final“. but it works exactly opposite to the “open” keyword, so let’s quickly understand the “final” keyword. I hope you all know about it, but don’t worry if don’t.

the “final” keyword is used in java mostly with classes and methods (functions) as:

final method : A method that cannot be overridden.

final class : A class that cannot be extended.

But, Kotlin has a special feature i.e. classes and methods are not open for extension by default, which means they are by default final class or final function. It means Open classes and methods in Kotlin are equivalent to the opposite of final in Java, an open method is overridable and an open class is extendable in Kotlin.

Note: your class is implicitly declared as open since it is abstract, hence you cannot create an instance of that class directly.

Examples

Example 1: Extension of class

Now we know that kotlin has everything final by default. So, if we try to extend the class then the compiler will show an error.

Источник

Читайте также:  Header in php with parameters
Оцените статью