Companions and Shared State
Lesson 35 of 48 in Coddy's Kotlin for Java Developers course.
Kotlin companion objects provide class-associated members; object declarations provide independent singletons. Instance property initializers run for each object, whereas companion state is shared. A val or const val restricts rebinding according to its rules, but a referenced mutable collection can still change. Prefer explicit per-instance ownership for independently evolving business state, and reserve shared members for intentional common metadata or services.
Java
import java.util.*;
import java.util.function.*;
public class Example {
static class Shelf{static final String KIND="storage";final List<String> books=new ArrayList<>();}
public static void main(String[] args){
Shelf a=new Shelf(),b=new Shelf();a.books.add("tea");System.out.println(b.books.size());
}
}Kotlin
class Shelf{companion object{const val KIND="storage"};val books=mutableListOf<String>()}
fun main(){
val a=Shelf()
val b=Shelf()
a.books.add("tea")
println(b.books.size)
}Porting trap
A companion mutable list would be shared by every instance.
Apply the concept in the separate exercise below. The demonstration uses a different operation or model; preserve the task file APIs and complete their required behavior.
Challenge
EasyInput is zero or more track-name lines, including empty names. Implement Playlist with companion constant category=music, add(track:String), and read-only size. Preserve duplicate tracks and keep independent lists per instance. Return category, size of the populated playlist, size of a fresh playlist.
Implement the editable files and return the result from Exercise.solve(input: List<String>). Do not print inside editable methods. The visible locked Main.kt reads all input lines and prints your returned text with one final newline. Text.kt supplies parsing and formatting helpers. All arithmetic results fit Int unless a narrower bound is stated.
Editable files: Playlist.kt, Exercise.kt, Text.kt. Only Main.kt has main; it is locked and is the last file. All files compile together in the same package.
The locked driver independently calls the required public APIs on fresh objects and alternate collaborators. Implement those behaviors; reproducing only fixture output is insufficient.
Try it yourself
fun main() {
val input = generateSequence { readlnOrNull() }.toList()
val a=Playlist();a.add("x");a.add("x");check(Playlist.category=="music" && a.size==2 && Playlist().size==0)
println(Exercise.solve(input))
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Kotlin for Java Developers
1Starting Kotlin
Run Your First KotlinStrings and TemplatesVal, Var, and TypesNumbers and ConversionsNullable Types and ElvisRecap: Receipt4Iteration and Transformations
While, Break, and ContinueLambdas and TransformationsSorting Without MutationDestructuring and IndexesRecap: Rank Scores7Classes and State
Classes and PropertiesConstructors and InitMethods and Bound ReferencesCompanions and Shared StateAccessors and InvariantsRecap: Bank Account2Values and Decisions
Equality and IdentityBoolean ConditionsIf and When ExpressionsRanges and For LoopsRecap: Eligibility3Collections and Ownership
Arrays and IntArrayRead-only and Mutable ListsMaps and Missing ValuesAliases and Shallow CopiesRecap: Unique Counts6Input, Errors, and Files
Input and String FormattingNullable Parsing and ErrorsFiles, Objects, and ImportsGenerics and List TypesRecap: Validate Records9Project: Order Processing
Project: Order ModelProject: Pricing PoliciesPractice on your own: Kotlin playground