Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add String?.shouldBeInteger([Int]): Int #1315

Merged
merged 2 commits into from
Mar 29, 2020

Conversation

SerVB
Copy link
Contributor

@SerVB SerVB commented Mar 28, 2020

Hi! I frequently do something like

val int = str?.toIntOrNull()
int.shouldNotBeNull()

// work with int

So I've defined shouldBeInteger function in my project and now it's like

val int = str.shouldBeInteger()

// work with int

Is it OK to add this function to the repo?

@sksamuel
Copy link
Member

Great idea, can we use contracts to smart case the type ?

@SerVB
Copy link
Contributor Author

SerVB commented Mar 28, 2020

You mean a contract for non-null like the following?

@OptIn(ExperimentalContracts::class)
fun String?.shouldBeInteger(radix: Int = 10): Int {
    contract {
        returns() implies (this@shouldBeInteger != null)
    }

    return when (this) {
        null -> throw failure("String is null, but it should be integer.")

        else -> when (val integer = this.toIntOrNull(radix)) {
            null -> throw failure("String '$this' is not integer, but it should be.")

            else -> integer
        }
    }
}

It doesn't make much sense to me because after this operation I don't work with the initial string. However, if you think it could be useful, I can add it.

@sksamuel
Copy link
Member

sksamuel commented Mar 28, 2020 via email

@SerVB
Copy link
Contributor Author

SerVB commented Mar 28, 2020

I think smart casting to Int is impossible here because there is still a String in a after this function returns.

But smart cast from String? to String is possible.

@sksamuel
Copy link
Member

sksamuel commented Mar 28, 2020 via email

@SerVB
Copy link
Contributor Author

SerVB commented Mar 28, 2020

Added the contract.

@sksamuel sksamuel merged commit 982ab13 into kotest:master Mar 29, 2020
@SerVB SerVB deleted the string-to-integer branch March 29, 2020 20:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants