Is there something more elegant instead of this sn...
# codingconventions
k
Is there something more elegant instead of this snippet (set to null and return the value that was before, raise exception if it was null previously)
Copy code
val previous = someField!!
someField = null
return previous
j
I find this pretty clear like this honestly. Although I would likely use
?: error("some meaningful message")
instead of
!!
. If you really want an alternative, you could do:
Copy code
return someField!!.also { someField = null }
But I'm not sure it's "more elegant"
r
`requireNotNull(someField) { "Some meaningful message" }`is another option; IMO it has a more clear intent than
!!
or
?: error(...)
.
k
Wait, so
return someField!!.also { someField = null }
will return the old value, not the null that's been set inside the { } block?
๐Ÿ‘Œ 2
j
@Richard Gomez It depends on whether this is a state error or an illegal argument. What you suggested is for illegal arguments. The equivalent of what you suggested for state errors would be
checkNotNull
. Now whether to use
checkNotNull
or
?: error()
depends on how you want the program to read. I find both acceptable under certain circumstances.
@Karlo Lozovina yes,
also
returns the value of its receiver. So first,
someField!!
is evaluated and passed to
also
as receiver, then
also
does its thing, and then it returns whatever value was initially given to it
๐Ÿ‘ 1
r
That's true; I just caution against
!!
in general because
requireNotNull
,
checkNotNull
, or
?: error()
result in clearer intent and error messages. I tend to see
!!
used in two scenarios: โ€ข "this can't be null, trust me, but the compiler isn't smart enough to determine this (e.g.
.filter { it != null }
) โ€ข "I have no idea what I'm doing and want these warnings to go away" ๐Ÿ˜„
๐Ÿ‘ 1
@Karlo Lozovina What Joffrey said; if you're curious,
.also { }
compiles to something like:
Copy code
public String foo() {
      String var10000 = someField;
      Intrinsics.checkNotNull(var10000);
      String var0 = var10000;
      int var2 = false; // I have no idea why this is here
      someField = (String)null;
      return var0;
   }
๐Ÿ‘ 2
j
Sometimes there is stuff in the bytecode to keep the line numbers or for debugging purposes, but I also have no idea why this particular extra variable is there ๐Ÿ™‚
k
thanks guys, cleared a few things for me! that
...also { }
block was confusing at first, it's getting late here ๐Ÿ™‚ I'm gonna go with
!!
, it's basically something that should never happen, so I'm going for brevity sake
.also {} block now reads kind of nice to me... going with it instead of manually doing what the compiler would do anyway ๐Ÿ˜„
๐Ÿ‘ 1