0

I'm learning Kotlin and would like to find out how to avoid creating an object if a function that is called inside an init block returns false. Basically, what I'd like to do is, if the function returns false, I'd throw the user an error and not create the object, but if it returns true, I'd create it. Does anyone know how I could solve this?

2
  • An if statement...? Commented Mar 28, 2021 at 17:00
  • For more specific use checkNotNull(fun) it's like check(), Otherwise returns the not null value. Commented Mar 28, 2021 at 18:57

1 Answer 1

3

You've just described everything yourself:

class MyClass {
    init {
        check(isValid())
    }

    private fun isValid(): Boolean {
        /* ... */
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.