Welcome back to CodeYourCraft! Today, we're diving into the world of Kotlin, a modern, concise, and powerful programming language used for Android development and more. We'll be focusing on Member Functions, which are a fundamental part of any object-oriented programming language. Let's get started! š
In Kotlin, member functions (also known as methods) are actions that an object or a class can perform. They are defined within a class and can manipulate the state of the object or perform some operation.
Let's consider an example of a simple Person class with a member function called sayHello().
class Person(val name: String) {
fun sayHello() {
println("Hello, $name!")
}
}š” Pro Tip: The val keyword is used to declare a read-only property.
class Person(val name: String): This line defines a class named Person with a constructor that accepts a String parameter named name.fun sayHello(): This line declares a member function named sayHello without any parameters.println("Hello, $name!"): This is the function body, which prints a greeting message using the name property.Now that we've defined our Person class, let's create an instance and use the sayHello() function.
fun main() {
val john = Person("John")
john.sayHello() // Output: Hello, John!
}In the main function, we create a new instance of the Person class named john with the name "John". Then, we call the sayHello() function on john to print the greeting message.
Kotlin supports various types of member functions, including:
What does the `val` keyword do in the context of Kotlin?
We'll explore these different types of functions in future lessons. Until then, happy coding! š