Practice Time: Pairs


Practice Time

Let's go through an example of getting information about a book in the format of a Pair. Generally, you want information about both the title and the author, and perhaps also the year.

  1. Let’s create a basic book class, with a title, author, and year. Of course, you could get each of the properties separately.
  2. Create a method that returns both the title and the author as a Pair.
  3. Create a method that returns the title, author and year as a Triple. Use the documentation to find out how to use Triple.
  4. Create a book instance.
  5. Print out the information about the book in a sentence, such as: “Here is your book X written by Y in Z.”


// TODO 1: Let’s create a basic book class, with a title, author, and year. Of course,
// you could get each of the properties separately.
class Book(val title: String, val author: String, val year: Int) {

// TODO 2: Create a method that returns both the title and the author as a Pair.
fun getTitleAuthor(): Pair<String, String> = (title to author)

// TODO 3: Create a method that returns the title, author and year as a Triple.
fun getTitleAuthorYear(): Triple<String, String, Int> = Triple(title, author, year)

}


// File:            Main.kt
// Programmer: Engineer Nolverto Urias Obeso
// Creation Date: 06/21/2023
// Email: nolvertou@gmail.com
// Description: Using pairs
// Activity: Let's go through an example of getting information about a book in the
// format of a Pair. Generally, you want information about both the title
// and the author, and perhaps also the year.

fun main() {
// TODO 3: Create a book instance.
val book = Book("Physics", "Nolverto", 2030)
println(book.getTitleAuthor()) // Output: (Physics, Nolverto)
println(book.getTitleAuthor().first) // Output: Physics
println(book.getTitleAuthor().second) // Output: Nolverto

println(book.getTitleAuthorYear()) // Output: (Physics, Nolverto, 2030)
println(book.getTitleAuthorYear().first) // Output: Physics
println(book.getTitleAuthorYear().second) // Output: Nolverto
println(book.getTitleAuthorYear().third) // Output: 2030

// TODO 4: Print out the information about the book in a sentence, such as:
// “Here is your book X written by Y in Z.”
println("Here is your book ${book.getTitleAuthorYear().first} " +
"written by ${book.getTitleAuthorYear().second} " +
"in ${book.getTitleAuthorYear().third}.")

// Output: Here is your book Physics written by Nolverto in 2030.

}

Comments

Popular posts from this blog