Bubble Sort | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/11447782-kotlin-whiteboard/lessons/28

Hi, in the other courses has something about use functions like this?
Because I say many implementations of bubble sort and that example I never saw the use of:

fun <T : Comparable> MutableList.bubbleSort(showPasses: Boolean = false) {

This it’s a type of function? Why use that?

<T : Comparable> MutableList

bubleSort it’s the name of the function?

It is Kotlin extension function with generic type.
Two things

  • MutableList.bubbleSort - extension function. When using this you can then invoke this function on a mutable list. Then while implementing this function - inside you are in context of mutable list so this refers to mutable list on which you invoked bubble sort.
  • - this means that mutablelist should consist of any type that extends Comparable interface. It can be type like Int. This enables us to compare two values.
    If you would like to implement bubble sort only for Int you might write it likt this fun MutableList<Int>.bubbleSort()