简体   繁体   中英

Conditional operator with Guava's Optional object in Java 7

I want to use the conditional operator in Java 7 where the returned object is com.google.common.base.Optional , something like this:

import com.google.common.base.Optional;
public Optional<String> getFirstElement(String str, String separator) {
    final String[] strs = str.split(separator);
    return strs.length == 0 ? Optional.absent() : Optional.of(strs[0]);
}

However, Optional.absent() has type Optional<?> instead of Optional<String> . Any idea about how to solve this?

On Java 7, just specify the type explicitly

public Optional<String> getFirstElement(String str, String separator) {
    final String[] strs = str.split(separator);
    return strs.length == 0 ? Optional.<String>absent() : Optional.of(strs[0]);
}

The Optional#absent() method is generic.

In Java 8, your code will compile fine thanks to some improved type inferrence.

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