2

I have the following Kotlin code:

fun getAdminUser(): User { return getAllUsers().first { it.userType == ADMIN } as User } 

If getAllUsers() doesn't have an element that matches the specified predicate, it throws a NoSuchElementException. I'm happy with this exception but would like to override the exception message to provide more context when it fails. Is it possible to do in Kotlin w/o try-catch?

2
  • 1
    getAllUsers().firstOrNull { it.userType == ADMIN } ?: throw NoSuchElementException("my custom exception message") Commented Jul 7, 2020 at 6:56
  • @AnimeshSahu, it doesn't work with the casting I have. Commented Jul 7, 2020 at 7:14

2 Answers 2

2

You could use the firstOrNull function to achieve that.

fun getAdminUser(): User { return (getAllUsers().firstOrNull { it.userType == ADMIN } as? User) ?: throw NoSuchElementException("Element not found") } 
Sign up to request clarification or add additional context in comments.

1 Comment

That solved my issue. And there's no need in wrapping the part before the Elvis operator in round brackets. Thanks!
0

Use firstOrNull to get first element or have null and use the elvis operator to throw NoSuchElementException.

fun getAdminUser(): User { val user = getAllUsers().firstOrNull { it.userType == ADMIN } ?: throw NoSuchElementException("My custom exception message") return user as? User ?: IllegalStateException("The element was neither null nor an instance of User class") } 

Otherwise to do it in single line you can do something like this:

fun getAdminUser(): User { return getAllUsers().firstOrNull { it.userType == ADMIN }?.also { require(it is User) { "The element was neither null nor an instance of User class" } } ?: throw NoSuchElementException("My custom exception message") } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.