enjoyable StarWarsMovie.releaseYear(): Int {
val yr = release_date.substring(0, 4)
return yr.toInt()
}
val newHope = StarWarsMovie("A New Hope", 4, "1977-05-25")
val releaseYear = newHope.releaseYear()
println("The discharge yr of A New Hope is $releaseYear")
Within the above instance, we’ve outlined a brand new technique on the category, referred to as releaseYear()
. Be aware that we outlined it instantly on the prevailing class: StarWarsMovie.releaseYear()
. We will do that with our personal courses, but additionally with courses imported from third-party libraries. The Kotlin documentation reveals an instance of including a way to the usual library. (I’m a bit cautious of this sort of monkey patching but it surely actually reveals Kotlin’s flexibility.)
Now, think about we wished StarWarsMovie
to be a subclass of a Film
superclass. In Kotlin, we may do one thing like this:
open class Film(val title: String, val releaseDate: String) {
open enjoyable releaseYear(): Int {
val yr = releaseDate.substring(0, 4) return yr.toInt()
}
}
class StarWarsMovie(title: String, episodeId: Int, releaseDate: String) : Film(title, releaseDate) {
val episodeId: Int = episodeId
}
The open
key phrase signifies {that a} class or operate is obtainable for subclassing or overriding. In Java phrases, Kotlin courses are ultimate by default. Default public members and default ultimate courses may very well be interpreted as delicate encouragement to want composition over inheritance. Within the previous instance, we used constructor-based declaration for each StarWarsMovie
and Film
. The colon in : film
signifies extension, working equally to Java’s extends
key phrase.