Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have some code:

private fun getTouchX(): Int {
    arguments ?: return centerX()

    return if (arguments.containsKey(KEY_DOWN_X)) {
        arguments.getInt(KEY_DOWN_X)
    } else {
        centerX()
    }
}

private fun centerX() = (views.rootView?.width ?: 0) / 2

and I want to shorten it.

in the function getTouchX, there are two return conditions duplicated. (which is centerX)

I tried to do this:

 private fun getTouchX(): Int {
    if (arguments == null || !arguments.containsKey(KEY_DOWN_X)) {
        return centerX()
    }
    return arguments.getInt(KEY_DOWN_X)
}

However, it looks more like Java than Kotlin.

How could I go about writing this in idiomatic Kotlin?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
175 views
Welcome To Ask or Share your Answers For Others

1 Answer

I'm not sure where arguments is coming from, but a cleaner solution would be

private fun getTouchX(): Int =
    if(arguments?.containsKey(KEY_DOWN_X) == true) {
        arguments.getInt(KEY_DOWN_X)
    } else {
        centerX()
    }

The if only calls containsKey if arguments is non-null, otherwise the left side of == resolves to null. null != true, so it will return centerX() from else.

Similarly if arguments is non-null, then the result of containsKey will be used to resolve.

And now that there's only one expression, can use body expression format.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...