KotlinCS 124 LogoJava
PrevIndexNext
Kotlin
Java
  • Implementing a Map : 04/26/2024

  • map-reduce-filter : 04/25/2024

  • Generics : 04/24/2024

  • Hashing : 04/23/2024

  • Binary Search : 04/22/2024

  • MP3: Course Ratings : 04/19/2024

  • Quicksort : 04/18/2024

  • Merge Sort : 04/17/2024

  • Sorting Algorithms : 04/16/2024

  • MP Debugging Part 1 : 04/15/2024

  • MP2: Course Activity : 04/12/2024

  • Practice with Recursion : 04/11/2024

  • MP Debugging Part 0 : 04/10/2024

  • MP2: API Client : 04/09/2024

  • MP2: API Server : 04/08/2024

  • Trees and Recursion : 04/05/2024

  • Trees : 04/04/2024

  • Recursion : 04/03/2024

  • MP1: Filtering and Search : 04/02/2024

  • MP1: Loading and Sorting : 04/01/2024

  • Lists Review and Performance : 03/29/2024

  • Linked Lists : 03/28/2024

  • Algorithms and Lists : 03/27/2024

  • Continuing MP0 : 03/26/2024

  • Getting Started with MP0 : 03/25/2024

  • Lambda Expressions : 03/22/2024

  • Anonymous Classes : 03/21/2024

  • Practice with Interfaces : 03/20/2024

  • Implementing Interfaces : 03/19/2024

  • Using Interfaces : 03/18/2024

  • Working with Exceptions : 03/08/2024

  • Throwing Exceptions : 03/07/2024

  • Catching Exceptions : 03/06/2024

  • References and Polymorphism : 03/05/2024

  • References : 03/04/2024

  • Data Modeling 2 : 03/01/2024

  • Equality and Object Copying : 02/29/2024

  • Polymorphism : 02/28/2024

  • Inheritance : 02/27/2024

  • Data Modeling 1 : 02/26/2024

  • Companion Objects : 02/23/2024

  • Encapsulation : 02/22/2024

  • Constructors : 02/21/2024

  • Objects, Continued : 02/20/2024

  • Introduction to Objects : 02/19/2024

  • Compilation and Immutability : 02/16/2024

  • Practice with Collections : 02/15/2024

  • Maps and Sets : 02/14/2024

  • Lists and Type Parameters : 02/13/2024

  • Imports and Libraries : 02/12/2024

  • Multidimensional Arrays : 02/09/2024

  • Practice with Strings : 02/08/2024

  • null : 02/07/2024

  • Algorithms and Strings : 02/06/2024

  • Strings : 02/05/2024

  • Functions and Algorithms : 02/02/2024

  • Practice with Functions : 02/01/2024

  • More About Functions : 01/31/2024

  • Errors and Debugging : 01/30/2024

  • Functions : 01/29/2024

  • Practice with Loops and Algorithms : 01/26/2024

  • Algorithms : 01/25/2024

  • Loops : 01/24/2024

  • Arrays : 01/23/2024

  • Compound Conditionals : 01/22/2024

  • Conditional Expressions and Statements : 01/19/2024

  • Operations on Variables : 01/18/2024

  • Variables and Types : 01/17/2024

  • Welcome to CS 124 : 01/16/2024

Lists and Type Parameters

val strings = mutableListOf<String>()
strings += "test"
println(strings)
strings += "me"
println(strings)

Next we’ll examine how to use Kotlin’s lists. We’ve stored sequential data before in an array, but lists are more flexible and more suited to certain tasks.

Debugging Challenge
Debugging Challenge

But let’s start with some debugging practice!

Lists
Lists

Like arrays, lists are an ordered data structure. However, unlike arrays, the size of a list can change as the program runs. This makes them much more appropriate for solving certain problems.

Kotlin has built-in lists. Let’s see how they work! (Open up the documentation as you follow along…)

// Kotlin Lists

Lists v. Arrays
Lists v. Arrays

Like arrays, Kotlin Lists store sequential data. In Kotlin, the syntax for using Lists is very similar to that for arrays, so it’s easy sometimes to even not be sure what you are working with! So let’s review the array operations we’re familiar with and show how they map onto Listss.

First, let’s show how we create an array and List, and check their size:

var array = arrayOf<String>() // empty Array to store Strings
println(array.size)
var list = mutableListOf<String>() // empty List to store Strings
println(list.size)

Note that with the List, unlike the array we do not need to specify a size when we create the List. This is because the size of a List can change!

Next up, how do we initialize a list with a set of values and print its contents? Just like arrays, that’s pretty easy!

var array = arrayOf("1", "2", "4")
println(array) // arrays don't print nicely by default...
var list = mutableListOf("1", "2", "4")
println(list) // lists print nicely!

We can access List contents using bracket notation, just like with arrays:

var array = arrayOf("1", "2", "4")
array[0] = "0" // bracket notation...
println(array[0])
var list = mutableListOf("1", "2", "4")
list[0] = "0" // and more bracket notation!
println(list[0])

List Add and Remove
List Add and Remove

Kotlin Lists provide both an add and a remove method, and also support += syntax for append. Let’s explore how they work:

var list = mutableListOf(1, 2, 4)
println(list)

Mutable and Immutable Lists
Mutable and Immutable Lists

Kotlin provides both mutable and immutable lists:

var first = listOf(1, 2, 4) // immutable list, contents cannot change
var second = mutableListOf(1, 2, 4) // mutable list, contents can change
first[0] = 0 // fails
second[2] = 8 // works

For now we’ll focus on using mutable lists in our code, as we’ve been doing above. But we’ll come back to this distinction later. For now, just keep this in mind, since it’s easy to forget and create an immutable list and then try to modify it, which doesn’t go well!

Note that the type for a Kotlin List is List, but the type of a mutable list is MutableList. However, Kotlin will convert a MutableList to a List automatically:

fun test(): List<String> {
var list = mutableListOf("1", "2", "4")
return list
}
println(test())

Practice: Small Word Filter With Array

Created By: Geoffrey Challen
/ Version: 2021.9.0

Write a method called smallWordFilter that, given a String containing words separated by single spaces (" "), returns all the words in the original String that are 3 characters or shorter in the same order in which they appeared in the original String, as an Array<String>.

For example, given the input "Xyz is the very best cat" you would return the Array<String> {"Xyz", "is", "the", "cat"}. We have skipped both "very" and "best" because they are longer than 3 characters.

This is a problem that would be much easier to solve using a list, since you don't know exactly how many part of the input String are 3 characters or smaller! But this can be done with an array, if somewhat awkwardly. Here's a solution sketch to help you get started:

  1. Split the array based on the single space " "
  2. Next, count the number of parts of the String that are 3 characters or smaller
  3. Now create your Array<String> of the appropriate size, initialized with empty Strings
  4. And then loop again through the array of String parts filling your output array as you go

We've provided some starter code to help you get going on this problem.

fun smallWordFilter(words: String): Array<String> {
val parts = words.split(" ")
var count = 0
// count words that meet the criteria
val toReturn = Array(count) { "" }
// now populate the toReturn array
return toReturn
}

Type Parameters
Type Parameters

The syntax that we introduce above is our first example of a Kotlin type parameter:

val list = mutableListOf<String>() // <String> is a type parameter
list.add("test")
println(list[0].length)

The <String> on the right tells Kotlin that this list will store Strings. If we wanted to store Ints, we’d use <Int> instead, Doubles, <Double>, and so on.

Why do lists require a type parameter? It’s so that we can tell Kotlin what we are going to put in them! Once we do, Kotlin will help us avoid common mistakes:

var strings = mutableListOf<String>()
strings += 1 // Can't append an `Int` to a `MutableList<String>`!

These mistakes are also caught before you program is run, at a step called compilation that we’ll explore later.

Type Parameters in Documentation
Type Parameters in Documentation

It’s important to understand how to identify type parameters when examining Kotlin documentation. Let’s do that together next.

Practice: Small Word Filter With List

Created By: Geoffrey Challen
/ Version: 2021.9.0

Write a method called smallWordFilter that, given a non-null String containing words separated by single spaces (" "), returns all the words in the original String that are 3 characters or shorter in the same order in which they appeared in the original String, as a List<String>.

For example, given the input "Xyz is the very best cat" you would return the List<String> containing {"Xyz", "is", "the", "cat"}. We have skipped both "very" and "best" because they are longer than 3 characters.

Note that you should not need any import statements, since Lists are built-in to Kotlin and always available.

intArray v. Array<Int>
intArray v. Array<Int>

Until this point, we’ve been using somewhat different approaches to creating arrays of Strings versus Kotlin basic types, like Int:

var strings = arrayOf<String>("1", "2", "4")
var ints = intArrayOf(1, 2, 4)

You’ll notice a type parameter in the String array, but no type parameter in the Int array, rather a special intArrayOf method.

It turns out that we can also use arrayOf<Int> in place of intArray. The differences are subtle, but worth a brief discussion:

// intArrayOf v. arrayOf<Int>

Don’t worry too much about this at this point. When you’re working with Int arrays, we’ll be sure to specify which one to use when it matters. And in general we’ll begin to use Kotlin lists to solve more problems now, since they are more convenient that arrays.

Homework: Stop Shouting List Filter

Created By: Geoffrey Challen
/ Version: 2022.9.0

Text-based communication over the internet is great! But let's avoid shouting at each other—meaning communicating using all caps, LIKE THIS!

Complete a method named removeShouting that accepts a List<String> and returns a new List<String> where any shouty words have been de-shouted—meaning any words that appear in all caps have been converted to lowercase. For example, given the input {"Please", "stop", "SHOUTING"}, you would return the list {"Please", "stop", "shouting"}. Note that only words that appear in all caps should be converted to lowercase—so "SHOUTING" in the example above but not "Please". You'll want to investigate various String methods to help you out with this problem.

CS People: Reshma Saujani
CS People: Reshma Saujani

Having a technical background isn’t a requirement for helping drive positive change in technology. Illini Reshma Saujani earned undergraduate degrees in Political Science and Speech Communication here at the University of Illinois, and graduate degrees from Harvard’s Kennedy School and Yale Law School. While a practicing lawyer and political aspirant, Saujani noticed the gender disparity in high school computer science classrooms, which caused her to found Girls Who Code in 2012 to encourage women to pursue technical careers.

She’s also spoken and written about female empowerment in the workplace. Her latest book, “Pay Up” was informed by her experience during the pandemic, and identifies structural forces in the American workplace that are harming women:

More Practice

Need more practice? Head over to the practice page.