Hacker News new | ask | show | jobs
by jillesvangurp 2014 days ago
Interesting. I kind of like how Kotlin provides syntactic sugar for this with ? and?: (and !! but you should avoid using that). I think Typescript integrated a similar feature last year.

However, Kotlin goes one step further and adds smart casting and contracts to the mix that enable the compiler to take null checks into account when inferring the type of something: String and String? are two different types so calling e.g. .length on a String? is a compile error. However, if you do a if(!s.isNullOrBlank()), s becomes a String. That gets rid of a lot of ugly code. Works for type checks as well. With contracts, you can tweak this further. And with extension functions you can add functionality to nullable types as well or generic types. The standard library has a few of those included.

For example let is an extension function defined as inline fun <T, R> T.let(block: (T) -> R): R

So if you have a String? you can write val message = s?.let { "hello %s" }

That works for any nullable type and basically one of the idioms in Kotlin that lets you avoid having to do null checks.

Typescript has absorbed quite a few similar features in recent years but it is being held back by backwards compatibility with Javascript. The two languages are actually very similar, especially if you turn on the strict mode. But there's always this untyped mess behind the facade that typescript provides. Currently, I'm dabbling with kotlin-js and I'm actually liking that as an alternative.