- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create an instance of an anonymous interface in Kotlin?
Kotlin has been developed over JVM, hence it supports most of the features of JVM. Java provides a feature called anonymous inner classes to handle the cases where we have to create an object of a class with a slight modification, without declaring a new subclass. An anonymous inner class doesn't have a name; we define it directly at the instantiation line.
However, Kotlin uses object expressions to provide the same sub-class functionality. In Kotlin, we can create an object expression of an interface by implementing its abstract methods. This implementation technique is known as anonymous interface.
Example – Anonymous Interface in Kotlin
The following example demonstrates how we can implement an anonymous interface in Kotlin.
fun interface myInterface<T> { fun call(context: T) } fun main() { val a = myInterface<String> { println("This is implementation of $it") } a.call("myInterface") }
Output
On execution, it will produce the following output −
This is implementation of myInterface