Objects

This Atom is Under Construction

The object keyword defines something that looks roughly like a class, except you can’t create instances of an object—there’s only one (you’ll sometimes see this referred to as the Singleton pattern).

An object is a way to combine functions and properties that logically belong together, but this “combination” doesn’t need multiple instances. Thus, you never create any instances of an object—there’s only one and it’s available once it’s been defined:

// Objects/ObjectKeyword.kt import atomictest.eq object JustOne { val n = 2 fun f() = n * 10 fun g() = this.n * 20 } fun main(args: Array<String>) { // val x = JustOne() // Error JustOne.n eq 2 JustOne.f() eq 20 JustOne.g() eq 40 }

Here, you can’t say JustOne() to create a new instance of class JustOne. That’s because the object declaration sets up the structure and creates the object at the same time.

End of sample. See AtomicKotlin.com for full early-access book.



Previous          Next

©2018 Mindview LLC. All Rights Reserved.