February 2018
Intermediate to advanced
356 pages
9h 10m
English
A companion object is an object which is common for all instances of that class. It means there are many instances of a book, for example, but there is a single instance of their companion object. Usually, the developers use companion objects as a factory method. Let's create our first companion object:
data class Book(val author:String,val name:String,val description:String,val new:Boolean = false{ companion object { fun create(name:String,description: String,author: String):Book{ return Book(author,name,description) } }}
If the name of the companion object was omitted, the function could be called in a singleton way, without an instance, like this:
val myBookWithFactory = Book.create("Claudio E. de Oliveira","Spring 5.0 ...