Common Contents
While Kotlin classes can hold lots of different sorts of programming constructs, the two most common are functions and properties. Just as we can define them outside of a class, we can define them inside of a class, for use by instances of that class.
Functions
Declaring an ordinary function is simply a matter of having the fun
be inside the body of a class:
class Foo {
fun something() {
println("Hello, world!")
}
}
Calling an object’s function is accomplished by using dot (.
) notation:
class Foo {
fun something() {
println("Hello, world!")
}
}
fun main() {
val foo = Foo()
foo.something()
}
You have access to the full range of capabilities that we describe in the chapter on functions: parameters, varargs, expression bodies, local variables, etc.
Properties
Just as classes can have functions, they can have properties:
class Foo {
var count = 0
fun something() {
count += 1
println("something() was called $count times")
}
}
fun main() {
val foo = Foo()
foo.something()
foo.something()
foo.something()
println("the final count was ${foo.count}")
}
Here, we have a count
property, initially set to 0
, that we increment on each call to something()
. That count
is then used in the printed output, courtesy of a bit of string interpolation.
Functions in the class can refer to properties just using the property name. Functions outside of the class, such as main()
, need to use dot notation, just like we do for calling functions on an object.
So, we get four lines of output: three from the something()
function that we are calling, and one from main()
itself:
something() was called 1 times
something() was called 2 times
something() was called 3 times
the final count was 3
However, properties in Kotlin can get surprisingly complicated. We will explore them in greater detail in an upcoming chapter.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.