Kotlin Member Functions šŸŽÆ

beginner
8 min

Kotlin Member Functions šŸŽÆ

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! šŸŽ‰

What are Member Functions? šŸ“

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().

kotlin
class Person(val name: String) { fun sayHello() { println("Hello, $name!") } }

šŸ’” Pro Tip: The val keyword is used to declare a read-only property.

Breaking it Down šŸ“

  • 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.

Using Member Functions šŸŽÆ

Now that we've defined our Person class, let's create an instance and use the sayHello() function.

kotlin
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.

Member Function Types šŸ“

Kotlin supports various types of member functions, including:

  1. Instance Functions: These are functions defined within a class that can be called on an instance of that class.
  2. Extension Functions: These are functions that can be added to existing classes without modifying the original source code.
  3. Object Functions: These are functions defined within an object, which can be called as instance functions.

Quiz Time šŸŽÆ

Quick Quiz
Question 1 of 1

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! šŸš€