4 Classes and functions
Classes in Kotlin follow a really simple structure. However, there are some slight differences from
Java that you will want to know before we continue. You can use
try.kotlinlang.org¹²
to test this and
some other simple examples without the need of a real project.
4.1 How to declare a class
If you want to declare a class, you just need to use the keyword
class
:
1
class MainActivity {
2
3
}
Classes have a unique default constructor. We’ll see that we can create extra constructors for some
exceptional cases, but keep in mind that most situations only require a single constructor. Parameters
are written just after the name. Brackets are not required if the class doesn’t have any content:
1
class Person(name: String, surname: String)
Where’s the body of the constructor then? You can declare an
init
block:
1
class Person(name: String, surname: String) {
2
init {
3
...
4
}
5
}
Do'stlaringiz bilan baham: