Kotlin: Object Expression and Object Declarations

Tram Ho

Hi everyone, back to the kotlin series, in this article we will learn two pretty good concepts in kotlin, Object Expression and Object Declarations, which are commonly used quite commonly and become useful in schools. well suited. Let’s explore through the concept and specific examples attached.

I. Context

Sometimes, in some cases, you need to create an object with minor modification of some class without explicitly declaring a new subclass for it.

Kotlin help us handle this case with Object Expression and Object Declarations.

I. Object Expression

The first is the Object Expression, which is actually a familiar concept to java programmers, it is equivalent to the Anonymous class concept in java, Anonymous class is defined as an expression and has no name. .

Object Expression is used to instantiate objects that can inherit from some classes or implement an Interface

We can also create an instance of an abstract class.

If a supertype has a constructor, the appropriate parameters of that constructor must be passed to it.

Multiple supertypes can be specified as comma separated.

In this case we only need to create an object, no supertypes is needed.

Where using an anonymous object:

Anonymous objects can only be used as types in local and private declarations.

If you use an anonymous object as the return type of a function / public property, the actual type of that function / property will be the declared supertype of an anonymous object or Any if it does not declare any supertype.

Members added to the anonymous object are inaccessible.

II. Object Declarations

Next will be the Object Declarations, used quite commonly as Object Expression.

Unlike Object Expression, Object Declarations always have a name after the object keyword. Just like a variable declaration.

An Object Declarations is not an expression, and cannot be used to assign.

Such objects can also have supertypes.

Note : Object Declarations cannot be local (ie nested directly inside a function) but they can be nested with other declarations or non-inner classes.

III. Conclusion

So we have learned Object Expression and Object Declarations in kotlin, through specific concepts and examples, know the use cases and accompanying notes.

Hope you can use it in real life project situations.

Thank you for reading, hello and see you in the next posts.

Refer: https://kotlinlang.org/docs/object-declarations.html#object-declarations

Share the news now

Source : Viblo