2016-08-04 6 views
8

Ich habe eine Methode, die java.util.Optional<Something> zurückgibt. Ich mag diese Methode von Kotlin verwenden, und ich mag mein Ergebnis Something?, nicht Optional<Something>Wie java.util.Optional <Something> zu etwas ordnen? in Kotlin

Wie die in Kotlin tun sein, in idiomatischem Weg?

Aufruf .orElse(null) auf Optional gibt mir Something? zwar, aber es sieht nicht gut aus. Kotlin beschwert sich nicht, wenn ich val msg: Something = optional.orElse(null). schreibe (msg wird als Something deklariert, nicht Something? - ich löse compile-type check).

verwende ich Kotlin 1.0.3

Antwort

13

die Java-API mit einer Methode erweitern Optional auszupacken:

fun <T> Optional<T>.unwrap(): T? = orElse(null) 

dann verwenden, wie Sie wollen:

val msg: Something? = optional.unwrap() // the type is enforced 

Siehe https://kotlinlang.org/docs/reference/extensions.html für Details .

+3

Kotlin-stdlib hat "oder-null" Funktionen (z.B. firstOrNull' '' lastOrNull', etc.). Sie könnten "orNull" statt "unwrap" verwenden. – mfulton26

1

orNull() ist besser.

Zum Beispiel

// Java 
public class JavaClass 
    public Optional<String> getOptionalString() { 
    return Optional.absent(); 
    } 
} 

// Kotlin 
val optionalString = JavaClass().getOptionalString().orNull() 

Die Definition von orNull()

/** 
* Returns the contained instance if it is present; {@code null} otherwise. If the instance is 
* known to be present, use {@link #get()} instead. 
* 
* <p><b>Comparison to {@code java.util.Optional}:</b> this method is equivalent to Java 8's 
* {@code Optional.orElse(null)}. 
*/ 
@Nullable 
public abstract T orNull(); 
Verwandte Themen