-
Interoperabilität Compiler: — Mischen von Java & Kotlin-Code problemlosem Zugriff in beide Richtungen
Misch-Betrieb
Misch-Betrieb: *.java, *.kt → *.class → *.dex Bidirektionale Beziehung → Graduell Hinzufügen möglich
Kotlin | Java |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Element | Beschreibung |
---|---|
|
Statische Methoden |
|
Singleton |
|
Property als Java Feld verfügbar machen |
@JvmName |
Bytecode/JVM Namen steuern |
@JvmOverloads |
Optionale Parameter ausmultiplizieren |
@Throws |
Checked exceptions Signatur deklarieren |
@Nullable / @NotNull |
|
Java / Kotlin
null
-Handlung bzw. Plattform Typespublic class Foo { public String getX() { return null; } } val a = Foo().x; println(a.lenght) // NPE
Annotationen
JetBrains, Android, JSR-305, FindBugs, Lombok
Fixed
public class Foo { @Nullable public String getX() { return null; } } val a = Foo().x; println(a.lenght) // compiler Error
Praxistipp:
-
NotNull programmieren und Nullable markieren.
-
Mann kann auch für ganze Pakete Defaults markieren 3.
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
Co- und Kontravarianz
class Consumer<in T> { fun consumeSomething(list: List<T>) { } } class Producer<out T> { fun produceSomething(): List<T> { TODO() } }
list.any({ i: Int -> i > 0}) list.any() { i: Int -> i > 0} list.any { i: Int -> i > 0} list.any { i -> i > 0} list.any { it > 0}
Standardbiliotheksfunktionen
listOf(1,2,3) mutableListOf(1,2,3) mapOf(1 to "eins", 2 to "zwei")
Equality
a == b | a?.equals(b) ?: (b == null) a < b | a.compareTo(b) < 0 a >= b | a.compareTo(b) >= 0 a in b | b.contains(a)
rangeTo
if (s in "abc".."def") { } for (i in 1..2) { }
destructuring
val (a,b) = p a = p.component1() a = p.component2()
enum class Color { BLUE, ORANGE, RED } fun indicateWeather(celsius: In) { val description: String val color: Color when { celsiusDegrees < 0 -> { description = "cold" color = Color.BLUE } celsiusDegrees in 0..15 -> { description = "mild" color = Color.ORANGE } else -> { description = "hot" color = Color.RED } } } fun updateWeather1(celsiusDegrees: Double) { val (description, color) = when { celsiusDegrees < 0 -> Pair("cold", Color.BLUE) celsiusDegrees in 0..15 -> "mild" to Color.ORANGE else -> "hot" to Color.RED } }