-1

I have the following code

val book = Book(
                id!!,
                title!!,
                image!!,
                subtitle!!,
                author,
                "",
                0,
                0
            )

I don't want to use !!. What's the correct way to write this code given that each value might be null?

Chris Scott
  • 5,388
  • 10
  • 53
  • 123

1 Answers1

1

If the values can be null, you should not prevent them from being passed in as null. We would say that those values are nullable and you can mark this by adding a question mark at the end of the type.

For example you could define the Book class as:

class Book(id: Int?, title: String?, ..)

and then you wouldn't need the force-unwrapping

val book = Book(id, title, image, subtitle, author, "", 0, 0)

But you might want to clarify what the last three values there are :)

jack
  • 446
  • 2
  • 9