enjoyable StarWarsMovie.releaseYear(): Int {
val 12 months = release_date.substring(0, 4)
return 12 months.toInt()
}
val newHope = StarWarsMovie("A New Hope", 4, "1977-05-25")
val releaseYear = newHope.releaseYear()
println("The discharge 12 months of A New Hope is $releaseYear")
Within the above instance, we’ve outlined a brand new methodology on the category, referred to as releaseYear()
. Notice that we outlined it straight on the prevailing class: StarWarsMovie.releaseYear()
. We will do that with our personal lessons, but additionally with lessons imported from third-party libraries. The Kotlin documentation exhibits an instance of including a technique to the usual library. (I’m a bit cautious of this type of monkey patching nevertheless it definitely exhibits Kotlin’s flexibility.)
Now, think about we needed 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 12 months = releaseDate.substring(0, 4) return 12 months.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 offered for subclassing or overriding. In Java phrases, Kotlin lessons are closing by default. Default public members and default closing lessons may very well be interpreted as refined encouragement to favor 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.