Set Toast gravity in Kotlin (error)?

I’m trying to display a toast message at the top of the screen.

I’m trying to display a toast message at the top of the screen. To do so, I’m using this code:

var toast = Toast.makeText(
    this,
    "Toast at top!",
    Toast.LENGTH_SHORT
)
toast.gravity = Gravity.TOP
toast.show()

However, I’m getting the error “Val cannot be reassigned” on the toast.gravity line.

To fix the “Val cannot be reassigned” error, you need to create a new Toast object with the required gravity and duration. Here’s the updated code:

val toast = Toast.makeText(
    this,
    "Toast at top!",
    Toast.LENGTH_SHORT
)
toast.setGravity(Gravity.TOP, 0, 0)
toast.show()

Note that setGravity() is used instead of directly modifying the gravity property, and it takes two additional arguments for x and y offsets, which can be set to 0 in this case.