How to Create Class in Kotlin: Syntax and Examples
In Kotlin, you create a class using the
class keyword followed by the class name and curly braces. Inside the braces, you can define properties and functions to describe the class behavior.Syntax
To create a class in Kotlin, use the class keyword, then the class name, and curly braces to hold properties and functions.
- class: keyword to declare a class
- ClassName: the name of your class (start with uppercase letter)
- { }: braces to contain class body
kotlin
class ClassName { // properties and functions go here }
Example
This example shows a simple Person class with a property and a function. It creates an object and prints a greeting.
kotlin
class Person(val name: String) { fun greet() { println("Hello, my name is $name") } } fun main() { val person = Person("Alice") person.greet() }
Output
Hello, my name is Alice
Common Pitfalls
Common mistakes include forgetting the class keyword, missing parentheses for the constructor, or not using val or var for properties in the primary constructor.
Also, avoid naming classes with lowercase letters, as Kotlin convention uses uppercase for class names.
kotlin
/* Wrong: missing class keyword */ // Person(val name: String) { } /* Wrong: missing val/var in constructor */ class Person(name: String) { } /* Right: correct class declaration */ class Person(val name: String) { }
Quick Reference
| Concept | Description | Example |
|---|---|---|
| class keyword | Declares a class | class MyClass { } |
| Primary constructor | Defines properties in class header | class Person(val name: String) { } |
| Property | Variable inside class | val age: Int = 30 |
| Function | Behavior inside class | fun greet() { println("Hi") } |
Key Takeaways
Use the
class keyword followed by the class name and braces to create a class.Define properties in the primary constructor using
val or var inside parentheses after the class name.Add functions inside the class body to describe behaviors.
Follow Kotlin naming conventions: class names start with uppercase letters.
Always include
val or var for constructor parameters to make them properties.