[OT] Some neat ideas from the Kotlin language
Jacob Carlborg via Digitalmars-d
digitalmars-d at puremagic.com
Fri Feb 19 04:16:49 PST 2016
On 2016-02-19 00:33, Yuxuan Shui wrote:
> Just come across Kotlin today, and found some interesting ideas skimming
> through its tutorial:
>
> 1) Null check
>
> Kotlin has Optional types, suffixed with a '?'. Like 'Int?', same as in
> Swift. But instead of explicitly unwrapping them (e.g. var! in Swift, or
> var.unwrap() in Rust), Kotlin let you do this:
>
>
> var: Int?
> if (var != null)
> //You can use var here
>
>
> Skipping the null check will get you compile time error.
>
> You can even do this:
>
> if (var == null) return;
> //You can use var from now on
I think the same applies to Swift. But I think you're supposed to use it
like this:
if let a = var {
// a is no unwrapped
}
I like the way it's used in Scala:
val a = Option(value)
val b = a.map(e => e /* do something with the unrapped e).getOrElse(/*
use a default value here */)
The Option type in Scala acts like a zero or one element collection. The
Scala way can be implemented in D as well without any language support.
> 2) Smart cast
>
> This is a similar to previous one, instead of:
>
> var1: Object;
> var2 = cast(String)var1;
>
> You do this:
>
> if (var1 is String)
> //You can use var1 as a String here
It's similar how it works in D, for Objects:
class Foo {}
Object foo = new Foo;
if (auto o = cast(Foo) foo)
// use o as Foo here
When casting to a subclass it will return null reference if the cast fails.
--
/Jacob Carlborg
More information about the Digitalmars-d
mailing list