Kotlinlearncs.online LogoJava

    ← Prev

    Index

    Next →

    Kotlin
    Java
    • 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

    Encapsulation

    class Person(private val age: Double) {
    var name: String = ""
    private set
    get() {
    return field + " " + field
    }
    fun updateName(setName: String) {
    name = setName
    }
    }
    val geoff = Person(42.0)
    geoff.updateName("Geoff")
    println(geoff.name)
    println(geoff.age)

    This lesson introduces us to both a big new idea, and a new programming pattern. We’ll show how Kotlin enables encapsulation (big new idea) through visibility modifiers and setters and getters (new programming pattern). This is cool stuff.

    So let’s get started!

    Encapsulation
    Encapsulation

    The new idea that we’re introducing in this lesson is encapsulation. Wikipedia defines it:

    In object-oriented programming (OOP), encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object’s components. Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties’ direct access to them. Publicly accessible methods are generally provided in the class (so-called “getters” and “setters”) to access the values, and other client classes call these methods to retrieve and modify the values within the object.

    Let’s unpack that definition together:

    Visibility Modifiers
    Visibility Modifiers

    OK great—so we want to keep some parts of our class private while allowing other parts to be public. But how do we do that?

    Kotlin provides multiple options. Here’s one:

    class Person(private val name: String, private val age: Double)

    Notice that we’ve introduced a visibility modifierprivate—to indicate that, while both the name and age should be set by the primary constructor, they are not available outside the class. Let’s talk a bit more about what that means:

    class Person(private val name: String, private val age: Double)

    Kotlin has two visibility modifiers. By default properties and methods are public—meaning that can be accessed by anyone. However, there are two other options:

    1. private: the property or method can be accessed or called only in code that is part of that class
    2. internal: this won’t make sense to us yet, but we’ll come back to it…

    For now we’ll stick to private and, when omitted, to public. We’ll discuss internal a few lessons from now. And keep in mind that if you don’t mark a method or field as private or internal, it ends up as public. This is normally the right thing, so it’s a good default for Kotlin to provide.

    Solve: Simple Object Method (Kotlin) (Practice)

    Created By: Geoffrey Challen
    / Version: 2021.2.0

    Create a class called Simple that stores a single mutable Int variable in a property named value. Also provide a method squared which returns the stored value, squared.

    Property Options
    Property Options

    When we declare properties in Kotlin as primary constructor parameters or within the class, Kotlin provides a reasonable set of defaults supporting common programming patterns. Here are some of our options.

    First option: public, set in the primary constructor, can be read and written outside the class after creation:

    class Person(var name: String)
    val geoff = Person("Geoff")
    println(geoff.name)
    geoff.name = "Geoffrey"
    println(geoff.name)

    Note that we can use val here if we want a variable that is only set in the primary constructor and can’t change afterward.

    Second option: public, not set in the primary constructor, can be read and written outside the class after creation:

    class Person {
    var name: String = ""
    }
    val geoff = Person()
    println(geoff.name)
    geoff.name = "Geoffrey"
    println(geoff.name)

    Third option: private, set in the primary constructor, can only be read and written by instance methods after creation:

    class Person(private var name: String) {
    fun printName() {
    println(name)
    }
    }
    val geoff = Person("Geoff")
    geoff.name = "Geoffrey" // doesn't work
    geoff.println(name) // instance methods can access name

    Fourth option: private, not set in the primary constructor, can only be read and written by instance methods after creation:

    class Person {
    private var name: String = ""
    fun changeName(setName: String) {
    name = setName
    }
    fun printName() {
    println(name)
    }
    }
    val geoff = Person()
    geoff.name = "Geoffrey" // doesn't work
    geoff.changeName("Geoffrey") // instance methods can access name
    geoff.printName()

    Let’s review these options together!

    class Person(var name: String)
    val geoff = Person("Geoff")
    println(geoff.name)
    geoff.name = "Geoffrey"
    println(geoff.name)

    Getters and Setters
    Getters and Setters

    However, there are times where we need a bit more control. Let’s see how to accomplish that by customizing the methods that Kotlin uses to change variable values.

    class Person(var age: Double)

    If these options seem confusing, don’t worry: we’ll get lots of practice at choosing the right approach for each situation that we encounter!

    Solve: Course Getters and Setters (Practice)

    Created By: Geoffrey Challen
    / Version: 2020.9.0

    Create a public class named Course. Course should store two pieces of data: a name (as a String?) using the property name and an enrollment (as an Int) using the property enrollment. Provide a constructor that allows both properties to be set, with the name first. The name property should be publicly readable but not publicly writable, while enrollment should be both publicly readable and writable. Finally, reject negative enrollment values and null names.

    Solve: Simple Object Method 2 (Kotlin)

    Created By: Geoffrey Challen
    / Version: 2021.9.0

    Create a class called Simple that stores a single mutable Int value in a property named value. Also provide a method inverse which returns the stored value multiplied by -1.

    CS People: Molly White
    CS People: Molly White

    While technology can be a force for good in the world, like anything else created by humans, its impact can easily go off in other directions. Molly White—a software engineer by trade—has established a reputation as a prominent critic of Web3 and cryptocurrencies, two technologies implicated in several recent scams and scandals. Her website, Web3 Is Going Just Great, provides a refreshing persepctive on the failures and follies in a very frothy space.

    In the interview below, Molly White discusses why crypto critics matter(1):

    More Practice

    Need more practice? Head over to the practice page.