Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn kotlin Examples


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:

  1. We define a class called Book with three properties: title, author, and year. These properties are initialized through the primary constructor.

  2. Inside the Book class, we define a method called displayInfo() that prints out the information about the book.

  3. In the main() function:

    • We create a list of Book objects using the listOf() function.
    • We iterate over each book in the list using a for loop.
    • Inside the loop, we call the 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.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java