I'm searching for the (idiomatic) Kotlin equivalent to javas:
private static Book currentBook;
public static Book get() {
if(currentBook == null) {
currentBook = new Book();
}
return currentBook;
}
public static void set(Book book) {
if(currentBook != null) {
throw IllegealStateException()
}
currentBook = book
}
My guess was
companion object {
var currentBook: Book? = null
get(): Book? {
if (field == null) {
field = Book()
}
return field
}
set(value) {
if(field != null) {
throw IllegalStateException()
}
field = value
}
}
The thing that bothers me is that currentBook is always non-null although I need to declared the type as nullable Book? to allow the default initialization with null.
Is there a proper way for a static property currentBook that is of non-nullable type Book?