Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

How would I write this in idiomatic Kotlin?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...