How and When to Use Kotlin Extension Functions

  • Reducing the number of classes necessary to build a modular, object oriented application (helps to manage class explosions which are a natural result of applying separation of concerns in an information system such as a computer program)
  • Extending the functionality of existing types, classes, and objects (source files), without requiring that you change their source code itself (for more information, look in to the Open-Closed Principle from SOLID Principles)
  • Making application code less repetitive (therefore more concise) and more legible (assuming you don’t write ugly and illegible names for your extensions)

Glossary:

Reducing Repetitive Code Without Inheritance


Toast.makeText(activity, value, Toast.LENGTH_SHORT).show()
//This could absolutely be made in to single expression syntax
internal fun Fragment.makeToast(value: String) { Toast.makeText(activity, value, Toast.LENGTH_SHORT).show()
}
//still works!
internal fun Activity.makeToast(value: String) {
Toast.makeText(this, value, Toast.LENGTH_SHORT).show()
}
//override is here simply because this class implements an interface
override fun showMessage(message: String) = makeToast(message)

Extending Functionality Without Modifying Existing Sources

internal val Note.toRegisteredRoomNote: RegisteredRoomNote    
get() = RegisteredRoomNote(
this.creationDate,
this.contents,
this.upVotes,
this.imageUrl,
this.safeGetUid
)
internal val RegisteredRoomNote.toNote: Note
get() = Note(
this.creationDate,
this.contents,
this.upVotes,
this.imageUrl,
User(this.creatorId)
)
class RoomLocalAnonymousRepositoryImpl(private val noteDao: AnonymousNoteDao) : ILocalNoteRepository {
override suspend fun deleteAll(): Result<Exception, Unit> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}

override suspend fun updateAll(list: List<Note>): Result<Exception, Unit> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}

override suspend fun updateNote(note: Note): Result<Exception, Unit> {
val updated = noteDao.insertOrUpdateNote(note.toAnonymousRoomNote)

return when {
//TODO verify that if nothing is updated, the resulting value will be 0
updated == 0L -> Result.build { throw SpaceNotesError.LocalIOException }
else -> Result.build { Unit }
}
}

override suspend fun getNote(id: String): Result<Exception, Note?> = Result.build { noteDao.getNoteById(id).toNote }


override suspend fun getNotes(): Result<Exception, List<Note>> = Result.build { noteDao.getNotes().toNoteListFromAnonymous() }


override suspend fun deleteNote(note: Note): Result<Exception, Unit> {
noteDao.deleteNote(note.toAnonymousRoomNote)
return Result.build { Unit }
}
}
internal fun List<AnonymousRoomNote>.toNoteListFromAnonymous(): List<Note> = this.flatMap {
listOf(it.toNote)
}

Closing Thoughts

  • Elimination of redundant code (Don’t Repeat Yourself!)
  • They can drastically improve code legibility if you use good names
  • They can allow you to extend the functionality of existing sources, such as Note, without having to modify their source itself

--

--

--

Self-taught software developer & student of computer science.

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

Recommended from Medium

IPFS (The Inter-Planetary File System)

2D Character Setup in Unity — Movement

Yes Devs Doing Sum Thing

How To Setup An OpenSea Account With MetaMask (Tutorial for Beginners 2022) To Sell Your First NFT

How To Setup An OpenSea Account With MetaMask (Tutorial for Beginners 2022) To Sell Your First NFT

Learning GraphQL

Backend development on Azure Functions with TypeScript

DAO Kapital

WaterlooWorks: Tips for Applications

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
Ryan Michael Kay

Ryan Michael Kay

Self-taught software developer & student of computer science.

More from Medium

Make your android smartphone to vibrate

Dynamically Update/Refresh/Reload ViewPager2 Fragments

Android Export and Import Data

ACTIVITY LIFECYCLE IN KOTLIN