The Kotlin Way: Coding approaches to implement interfaces

Inspiration

Implementing intefaces from Java world

public interface Calculator<T> {
int add(T a, T b);
}

Approach #1: Classic

// Kotlin Implementation #1
class IntegerCalculator : Calculator<Int> {
override fun add(a: Int, b: Int): Int {
return a + b
}
}
// Invocation
val integerCalculator = IntegerCalculator()
integerCalculator.add(2, 3)

Approach #2: Object expressions

val integerCalculator = object : Calculator<Int> {
override fun add(a: Int, b: Int): Int {
return a + b
}
}
print(integerCalculator.add(1, 2))

Approach #3: Uncle Sam in Java Interfaces

val integerCalculator = Calculator<Int> { a, b -> a + b }
integerCalculator.add(2, 3)
public interface Calculator<T> {
T square(int x);
}

Object expressions approach

val integerCalculator = object : Calculator<Int>{
override fun square(x: Int): Int {
return x*x
}
}
integerCalculator.square(2)

The Kotlin Way: Passing in a lambda expression

val integerCalculator = Calculator { it * it }
integerCalculator.square(2)

Uncle Sam in Kotlin intefaces?

But that doesn’t make sense!

class Calculator<T>(private val squareOperation: (x: T) -> T) {
fun square(x: T): T {
return squareOperation(x)
}
}
// Invocation
val integerCalculator = Calculator<Int> { x -> x * x }
integerCalculator.square(2)

--

--

--

Building the future, one BLOCK at a time. Blockchain R&D engineer @PersistentSys.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Missing Column after Migration to S3 Using DMS

Growth Hacking: How to get (scrape) a product catalogue from an e-commerce site

To SQL or to NoSQL? That is the Question

x64 SLAE — Assignment 2: Reverse Shell

What are Coroutines in Unity?

Growth Mindset

What is Amazon Elastic Load Balancer (ELB)

Short review of CI/CD tools in 2020

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amol Pednekar

Amol Pednekar

Building the future, one BLOCK at a time. Blockchain R&D engineer @PersistentSys.

More from Medium

How to launch an Instant app to production on the Google Play Store

Google Instant app — How to publish it

Some pros of Moshi over Gson when using Kotlin for Android

Paytm Payment Gateway Integration on Android Studio

Product release: react-channel and adding Kotlin