How to create an instance of anonymous interface in Kotlin?
In Kotlin, you can instantiate an anonymous interface by using object expression. You define the interface in the variable declaration as follows:
In the above snippet, you declare a variable with val
, assign it a name, and use object :
along with the interface name, then provide the function overrides in the braces { }
.
Instantiate a SAM interface with a lambda
A single abstract method (SAM) interface can be represented too using a lambda. When the interface you're implementing only has one method, Kotlin allows for a much more compact form:
It's equivalent to an anonymous instance but with a lambda for simplicity. Be aware that SAM conversions are only applicable for interfaces with a single abstract method.
Lambdas and function interfaces: Less is more
Lambdas in Kotlin offer a neat way of implementing functional interfaces. You can use a lambda to create instances of functional interfaces, making your code concise and easy to read.
The above assumes that Handler
is a functional interface or a SAM interface from Java. By using lambdas, you can say goodbye to unnecessary verbosity.
When you've more than one method in an interface
When you are dealing with multiple methods in an interface, you can't use the SAM conversions. Here, you need to use the keyword object:
Remember to override all the abstract methods in the interface.
Practical applications and specific scenarios
How Android utilizes anonymous classes
In Android development, instantiating anonymous classes is common in handling events, such as button clicks. As these events are often single-method interfaces, SAM conversions can be effectively utilized.
The code block above is Kotlin's syntax sugar to implement the OnClickListener
interface that is equipped with a single abstract method, well-known as the onClick
.
Harnessing the power of type-safe builders
Using Kotlin's type-safe builder pattern, you can create DSLs and thereby use anonymous interfaces. Following is an example:
In this case, each such function like html
, head
, body
, a
, etc., most likely have a builder interface, which might be an instance of anonymous interface internally.
Problematic areas and workarounds
When making a transition from Java to Kotlin, you might encounter issues with Java SAM interfaces compatibility. Ensure that the Kotlin equivalent is marked as a fun interface
to maintain the concise lambda syntax.
Typos in method signatures when declaring an anonymous class can lead to new methods, instead of overriding the interface methods. Always use the override
keyword to avoid such situations. Remember, compiler is your lighthouse.
Was this article helpful?