-> $v") } someObject?.let { // execute this block if not null } fun foo(param: Int) { val result = if (param == 1) { "one" } else if (param == 2) { "two" } else { "three" } }
f() { print("A") } fun a() { print("a") } } interface B { fun f() { print("B") } fun b() { print("b") } } class C() : A(), B { // The compiler requires f() to be overridden: override fun f() { super<A>.f() // call to A.f() super<B>.f() // call to B.f() } }
all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement.
String = “kotlin is awesome" str = null // compilation error… str is non-nullable type var str: String? = “kotlin is awesome" str = null // ok... str now can be null val length = name.length // compilation error val length = name?.length // ok
in java Collections.sort(items, new Comparator<MyClass>() { @Override public int compare(MyClass t1, MyClass t2) { return t1.getName().compareTo(t2.getName()); } });
List<R> { val result = arrayListOf<R>() for (item in this) result.add(transform(item)) return result } val doubled = items.map { it * 2 } fun <T> max(collection: Collection<T>, less: (T, T) -> Boolean): T? { var max: T? = null for (it in collection) if (max == null || less(max, it)) max = it return max } val less = {a:Int,b:Int -> a > b}