Sitemap
Mobile App Development Publication

Sharing iOS, Android and relevant Mobile App Development Technology and Learning

Follow publication

Member-only story

In and out type variant of Kotlin

If you ever defined generic in Kotlin, you’ll notice many a times, it would propose to use the in or out keyword to define the generic. It puzzles me at a start on when which is used, and for what.

Formally, this is a way to define contravariance and covariant. It took me a while to learn about it. I’ll dive in here to explain what how I understand and memorize their different.

In & Out easily remembered

Out (covariant type)

If your generic class only use the generic type as output of it’s function/s, then out is used i.e.

interface Production<out T> {
fun produce(): T
}

I call it production class/interface, as it is mainly to produce output of the generic type. Hence very simple one could remember

produce = output = out.

In (contravariance type)

If your generic class only use the generic type as input of it’s function/s, then in is used i.e.

interface Consumer<in T> {
fun consume(item: T)
}

I call it consumer class/interface, as it is mainly consuming the generic type. Hence very simple one could remember

consume = input = in.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Mobile App Development Publication
Mobile App Development Publication

Published in Mobile App Development Publication

Sharing iOS, Android and relevant Mobile App Development Technology and Learning

Elye - A One Eye Dev By His Grace
Elye - A One Eye Dev By His Grace

Written by Elye - A One Eye Dev By His Grace

Sharing Software, Life and Faith Journey. Follow me on Twitter/X to access to my article free

Responses (11)

Write a response