Sure, let's create a simple Kotlin example that demonstrates the basics of the language.
Let's say we want to create a program that manages a list of books. Each book will have a title, an author, and a publication year. We'll create a class to represent a book, and then we'll create a simple program to interact with a list of books.
Example
// Define a class to represent a book
class Book(val title: String, val author: String, val year: Int) {
// Method to display information about the book
fun displayInfo() {
println("Title: $title")
println("Author: $author")
println("Year: $year")
println()
}
}
fun main() {
// Create a list of books
val books = listOf(
Book("To Kill a Mockingbird", "Harper Lee", 1960),
Book("1984", "George Orwell", 1949),
Book("The Catcher in the Rye", "J.D. Salinger", 1951)
)
// Display information about each book in the list
for (book in books) {
book.displayInfo()
}
}
Here's what's happening in this example:
We define a class called Book
with three properties: title
, author
, and year
. These properties are initialized through the primary constructor.
Inside the Book
class, we define a method called displayInfo()
that prints out the information about the book.
In the main()
function:
Book
objects using the listOf()
function.for
loop.displayInfo()
method on each book to print its information.When you run this program, it will output the information about each book:
Example
Title: To Kill a Mockingbird
Author: Harper Lee
Year: 1960
Title: 1984
Author: George Orwell
Year: 1949
Title: The Catcher in the Rye
Author: J.D. Salinger
Year: 1951
This example demonstrates basic class definition, object creation, and method invocation in Kotlin.