by kragen · 11y ago · 0 comments
Now that I know that, Kotlin looks pretty cool! It proposes solutions to a lot of the most painful problems in Java.
I'm not sure the solutions are always correct, though. When I hear "null safety", I think "pattern matching on a Maybe sum type to statically ensure non-nullness", but what the talk says Kotlin actually provides is pressuring you into writing a bunch of your code in the Maybe monad, thus spreading nullness far and wide. The talk example is "println(a?.length())".
Maybe that's the best pragmatic solution in Kotlin, or maybe the talk oversimplifies what Kotlin actually gives you, but it kind of seems like the wrong direction to go in to me (most of the time!)
Kotlin allows non-nullable reference types, so you can declare a method as taking a non-nullable reference to an object. Now within that method, you know that reference is never null, and don't need to check it. When you call it, you have to either check for null beforehand, or pass something that is already guaranteed not to be null.
It's kind of like it builds a wall between things that could be null, and things that can't be, instead of having theoretical potential nulls all over your code. When you think about it, it seems like a pretty natural thing for a strongly-typed language to do.
fun myFunc(a: Int?): {
if ( a == null ) {
// handle the null case
}
// a is guaranteed non-null here
}
EDIT: And, of course, you can just use non-nullable types: fun myFunc(a: Int) {
// a is guaranteed non-null
}