Practice Time: Extension Functions
Practice Time
It can be useful to know the weight of a book, for example, for shipping. The weight of a book can change because sometimes pages get torn, and the page count changes. While calculating the weight could be defined as a method, it’s more like a helper function. Besides, it would hurt a book's feelings to have a method that tears up its pages.
- Add a mutable property
pages
toBook
. - Create an extension function on
Book
that returns the weight of a book as the page count multiplied by 1.5 grams. - Create another extension,
tornPages()
, that takes the number of torn pages as an argument and changes the page count of the book. - Write a class
Puppy
with a methodplayWithBook()
that takes a book as an argument, and removes a random number of pages from the book. - Create a
puppy
and give it abook
to play with, until there are no more pages.
Main File
// File: Main.kt
// Programmer: Engineer Nolverto Urias Obeso
// Creation Date: 06/24/2023
// Email: nolvertou@gmail.com
// Description: Using extension functions
fun main() {
// TODO 5: Create a puppy and give it a book to play with, until there are no more pages.
val puppy = Puppy()
val book = Book("A Practical Guide to Adopting UVM", "Sharon Rosenberg", 2011, 320)
while(book.pages > 0){
puppy.playWithBook(book)
println("${book.pages} left in ${book.title}")
}
println("Sad puppy, no more pages in ${book.title}. ")
}
// TODO 2: Create an extension function on Book that returns the weight
// of a book as the page count multiplied by 1.5 grams.
fun Book.weight(): Double = pages * 1.5
// TODO 3: Create another extension, tornPages(), that takes the number of torn pages as
// an argument and changes the page count of the book.
fun Book.tornPages(tornPages: Int) = if (pages >= tornPages) pages -= tornPages else pages = 0
Book Class
// TODO 1: Add a mutable property pages to Book.
class Book(val title: String, val author: String, val year:Int, var pages: Int) {
}Puppy Classimport java.util.Random
// TODO 4: Write a class Puppy with a method playWithBook() that takes a book as an argument,
// and removes a random number of pages from the book.
class Puppy {
fun playWithBook(book: Book){
book.tornPages(Random().nextInt(8))
}
}
Comments
Post a Comment