Learn
Using Text Variables
Built-in Properties and Functions

Kotlin contains built-in properties and functions that can be used with its various data types. We’ll be looking at the most common built-in property and function for variables of the String type. You can access the full list in Kotlin’s documentation.

In short, a property provides information on a particular value. Kotlin supports a single String property, length which returns the number of characters in a String. Let’s see an example:

val tallestMountain = "Mount Everest" print(tallestMountain.length) // Prints: 13

The number of characters in "Mount Everest" equates to 13. Notice how the whitespace is also included in the count.

In addition, a String data type also contains built-in functions that can be used to perform certain actions on the String it’s appended on. For example, the capitalize() function returns a capitalized String:

var name = "codecademy" println(name.capitalize()) // Prints: Codecademy

Note that although the returned value is Codecademy, the original lowercase String, "codecademy", goes unchanged:

println(name) // Prints: codecademy

To persist any changes made by the function, we can reassign the result of name.capitalize() to name and update the variable:

name = name.capitalize() println(name) // Prints: Codecademy

Or we can store the result in an entirely new variable:

var capitalizedName = name.capitalize() println(capitalizedName) // Prints: Codecademy

Note: Characters have their own built-in properties and functions in Kotlin. Reference this page in Kotlin’s documentation for a list of all of them.

Instructions

1.

In MaryPoppins.kt, below the initialization of the given variable, reassign the value of word to the result of word.capitalize(). Make sure to do this on one line.

2.

On the following line, declare a variable, wordSize and initialize it with the result of appending the length property on word.

Next, use a String template or String concatenation within a print statement to output the following text:

[word] has [wordSize] letters.

Replace the brackets with the correct notation.

Folder Icon

Take this course for free

Already have an account?