简体   繁体   中英

The Difference {}, () in kotlin null check

I'm practicing null checking in kotlin When I use Elvis operator ?: I use {} but the correct way is using () . But My mistake, the result was wrong.

My Mistake Codes are below.

var name: String = "eunno"//NonNull
val lastName: String? = null
val fullName = name + " " + {lastName ?: "No lastName"}
  1. Result when use {}

    eunno Function0<java.lang.String>
  2. Result when use ()

    eunno No lastName

I don't understand the difference of results. Is there any difference about using {} , () ?

Except for some specific cases, in Kotlin { … } defines a lambda . That's a function with no name; it won't evaluate the contents yet, but you can pass it to other code which will.

That differs from ( … ) , which simply groups an expression that's evaluated in the normal way.

There are two reasons why this may seem a little confusing:

  1. It differs from most other languages, which use braces only for grouping code into blocks, and/or which require some other syntax when defining lambdas (eg -> , => , or lambda ).

  2. The exceptional cases in Kotlin are very commonly used:

    • Defining classes and interfaces: class MyClass { … }
    • Defining functions: fun myFun() { … }
    • Blocks in for , while , if…else , when , and try…catch…finally constructs: while (condition) { … } etc.

In practice, most of the braces you see in Kotlin fall into the above cases, so it can be easy to miss the fact that they mean something else in all other cases.

It's done this way because in Kotlin, if a lambda has less than two parameters, you don't need to give the usual parameter name or -> . (If it takes one parameter, you can just refer to that as it , which is usually easier to read.) Since you need some way to indicate a lambda, Kotlin requires the braces instead.

The other benefit is that it lets you write library functions that look like new language synax. This works because if the last parameter to a function is a lambda, you can put it outside the parens — and even omit the parens entirely if there are no other parameters. That's why you can write eg:

with (myObject) {
    // Here 'this' refers to myObject.
}

with is a simple function in the standard library. But it looks like a language construct (similar to while ) — as do run , let ,repeat , and many others. And you can write your own functions that can be called in just the same way!

Lambdas are widely used in Kotlin, and it's well worth getting to know them. And then you should find this (slightly idiosyncratic) bit of syntax clearer!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM