I've heard people saying that you should never hav...
# effective-kotlin
f
I've heard people saying that you should never have nullable variables in kotlin, and "It's just a remnant from Java". What do you think about that?
t
that's nonsense i think.
null
has it's application and kotlin allows us to be aware of nullable values in a very clever way. E.g. consider a
Repository<Entity>
that has a
fetchById(id: IdClass)
method. what would you expect it to do? throw an exception if
id
is unknown? Return
FetchResult
instead of
Entity
which would be dfined as
Copy code
sealed  class FetchResult {
   object NoResult: FetcHresult
  class SingleResult(val result: Entity): FetchResult
  
}
i think this approach is way over engineered - why not rturn
Entity?
?
d
If you haven’t looked at Roman’s post about nullability yet, check it out, it resonates with this discussion very well: https://medium.com/@elizarov/null-is-your-friend-not-a-mistake-b63ff1751dd5
👍 2
1
r
Something I’ve been trying out in order to get around repo-layer cases like that is by taking a function parameter with the expected object type as the receiver. At the call site, it looks like this
Copy code
repo {
  with(myObjId) {
    //do work on MyObj-type
  }
}
the repo interface looks like this
Copy code
operator fun invoke(action: Repo.() -> Unit)
fun with(id: String, action: MyObj.() -> Unit)
Theoretically, you could establish a
notFound
function parameter to define a different set of work in the case that the object could not be retrieved.