Kotlinlearncs.online LogoJava

    ← Prev

    Index

    Next →

    Kotlin
    Java
    • map-reduce-filter : 58

    • Generics : 57

    • Implementing a Map : 56

    • Hashing : 55

    • Binary Search : 54

    • Quicksort : 53

    • Merge Sort : 52

    • Sorting Algorithms : 51

    • Practice with Recursion : 50

    • Trees and Recursion : 49

    • Trees : 48

    • Recursion : 47

    • Lists Review and Performance : 46

    • Linked Lists : 45

    • Algorithms and Lists : 44

    • Lambda Expressions : 43

    • Anonymous Classes : 42

    • Practice with Interfaces : 41

    • Implementing Interfaces : 40

    • Using Interfaces : 39

    • Working with Exceptions : 38

    • Throwing Exceptions : 37

    • Catching Exceptions : 36

    • References and Polymorphism : 35

    • References : 34

    • Data Modeling 2 : 33

    • Equality and Object Copying : 32

    • Polymorphism : 31

    • Inheritance : 30

    • Data Modeling 1 : 29

    • Companion Objects : 28

    • Encapsulation : 27

    • Constructors : 26

    • Objects, Continued : 25

    • Introduction to Objects : 24

    • Compilation and Immutability : 23

    • Practice with Collections : 22

    • Maps and Sets : 21

    • Lists and Type Parameters : 20

    • Imports and Libraries : 19

    • Multidimensional Arrays : 18

    • Practice with Strings : 17

    • null : 16

    • Algorithms and Strings : 15

    • Strings : 14

    • Functions and Algorithms : 13

    • Practice with Functions : 12

    • More About Functions : 11

    • Errors and Debugging : 10

    • Functions : 9

    • Practice with Loops and Algorithms : 8

    • Algorithms I : 7

    • Loops : 6

    • Arrays : 5

    • Compound Conditionals : 4

    • Conditional Expressions and Statements : 3

    • Operations on Variables : 2

    • Variables and Types : 1

    • Hello, world! : 0

    Generics

    class Counter<T>(private val value: T) {
    var count = 0
    private set
    fun add(newValue: T) {
    if (value == newValue) {
    count++
    }
    }
    }
    val counter = Counter(4)
    assert(counter.count == 0)
    counter.add(4)
    assert(counter.count == 1)
    counter.add("test") // fails

    Next we’ll examine Kotlin generics. This is an advanced topic, but one that you are bound to encounter as you continue to use Kotlin. Generics also allow the compiler to better check our code—and we always want that. So let’s do this!

    Using Generics
    Using Generics

    We’ve already seen generics at use when using Kotlin’s containers like Lists, which require a type parameter when Kotlin cannot infer it:

    val first = listOf(1, 2, 4) // inferred as a List<Int>, no type parameter required
    val second: List<String> = listOf() // empty List<String>
    val third = listOf<String>() // another empty List<String>

    Remember: runtime errors cause things to fail right in the user’s face. This is not good! Compiler errors, in contrast, must be caught in development. So transforming runtime errors to compiler errors helps us produce more correct programs. This is good! Because Kotlin knows what is stored in the list, it knows what we can and can’t do with the list contents:

    val first = listOf(1, 2, 4)
    println(first.sum())
    val second = listOf("one", "two", "four")
    println(second.sum()) // fails

    Generifying Our Classes
    Generifying Our Classes

    OK—so now we know how to use classes that accept type parameters. But how about using the in our own classes? This turns out to not be too hard! Let’s explore together.

    To start, let’s design a class that does not support type parameters, but can still accept any object by using Any:

    class LastN {
    }

    Next, let’s look at how to add a generic type parameter to our example above. This will allow the compiler to ensure that all of the values added to LastN are the same type!

    class LastN {
    }

    Compiling Generic Classes
    Compiling Generic Classes

    There are a few important things to understand about how Kotlin compiles generic classes. First, the type parameter is not a variable. You can use them in most places that you would normally use a type, but you can’t assign to them:

    class Example<E> {
    var value: E? = null
    fun test() {
    E = String // But you can't reassign a type parameter
    value = E() // Also doesn't work, since maybe E doesn't have an empty constructor?
    }
    }

    One useful way to think about what happens when your program is compiled is that the compiler replaces the type parameters with types used in your code. So, given this generic class:

    class Example<E>(val value: E)

    If I create a Example<String>, it’s almost as if I had written this code:

    class Example(val value: String)

    Type Parameter Naming Conventions
    Type Parameter Naming Conventions

    You can use any name to name your type parameters. But Kotlin inherits Java’s established conventions. Specifically:

    Parameterized Interfaces
    Parameterized Interfaces

    Just like Kotlin classes, interfaces can also accept type parameters. That includes one interface that we are fairly familiar with by now!

    class Dog(private val name: String)

    One Big Generic Gotcha
    One Big Generic Gotcha

    You may have noticed above that when we implemented LastN we used a List rather than an array. That wasn’t an accident! Let’s see why and what problems arise with generic arrays.

    class LastN

    Bounded Type Parameters
    Bounded Type Parameters

    (What follows is bonus bonus material, but very cool!)

    Let’s consider another example where we’d like to use generics:

    class Maximum<E>(initialMaximum: E) {
    var maximum = initialMaximum
    private set
    fun add(newValue: E) {
    // Change the maximum if newValue is bigger
    }
    }

    Let’s explore how we can complete the example above using another feature of Kotlin’s generics system: bounded type parameters.

    class Maximum<E>(initialMaximum: E) {
    var maximum = initialMaximum
    private set
    fun add(newValue: E) {
    // Change the maximum if newValue is bigger
    }
    }

    And There’s More…
    And There’s More…

    This lesson has barely scratched the surface of what is possible with Kotlin generics. If you want to learn more, this is a good place to start.

    Generics in Kotlin Documentation
    Generics in Kotlin Documentation

    You regularly see generic type parameters in Kotlin documentation. Now that we’ve discussed a bit about how to use type parameters in our own code, we’re more prepared to understand documentation for classes that use them. Let’s look at one familiar example together and discuss how to identify and interpret these type parameters.

    Solve: BinaryTree Balanced

    Created By: Geoffrey Challen
    / Version: 2020.11.0

    Let's determine if a binary tree is height balanced. A tree is height balanced if the height of any node's two subtrees (right and left) never differ by more than 1.

    Provide a method named isBalanced. isBalanced accepts a BinaryTree<*> and returns true if the tree is balanced, and false otherwise.

    A few hints on this problem:

    • Your main entry point method will probably need to start the recursion using a private helper method, because the main method doesn't accept nullable trees which you want to handle as a valid base case in your recursion
    • This helper method will probably have the same arguments as the main method, so you'll need to change something else to make sure that the method signature is different and the compiler can determine which one you want to use
    • You will probably need a second helper method implementing tree height that you call in your primary recursive method

    More Practice

    Need more practice? Head over to the practice page.