#2539 Str.getSafe() not nullable

SlimerDude Mon 23 May 2016

Presumably Str.getSafe() is akin to List.getSafe() but List.getSafe() has a nullable default value:

V? getSafe(Int index, V? def := null)

meaning that it returns null should the index be out of bounds / does not exist. This makes it useful as I can chain it with elvis:

list := Str[,]
item := list[13] ?: "Not found"

I also often use elvis to throw my own Errs that provide more context to the problem:

item := list[13] ?: throw ArgErr("Could not that very important thing in ${list}")

Then, when trying to do the same with Str.getSafe() I noticed that is not-nullable:

Int getSafe(Int index, Int def := 0)

Meaning I can't use elvis, or distinguish between not-found and the character value 0. Granted, 0.toChar is not a printable character, but it is a valid ASCII character non the less.

So I was wondering what the reasoning is / was for using such an odd default value? I would have thought null to be more correct than 0.

brian Tue 24 May 2016

Its not nullable for performance reasons - making nullable requires boxing the chars to a java.lang.Long

Login or Signup to reply.