v79
11/29/2021, 8:33 AMclass Grid(val x:Int, val y: Int)
but in some cases there won't be a value. Rather than make it nullable, I'd like to be able to return something like Grid.NONE
instead. But not sure if this is a case for sealed classes, or interfaces, or an enum... I don't want to make Grid
open, and it's likely that Grid
will expand with additional properties and functions over time. Any suggestions?Dominaezzz
11/29/2021, 8:36 AMTies
11/29/2021, 8:36 AMv79
11/29/2021, 8:39 AMsealed interface TileGrid
class Grid(val x: Int, val y: Int) : TileGrid
object NONE : TileGrid
Ties
11/29/2021, 8:44 AMfun getGrid() : Grid?
getGrid()?.let{ println(it) }
is not a bad thing to do in kotlin. So it kinda depends on the rest of your application and how you use the function resultRob Elliot
11/29/2021, 8:57 AMnull
to mean no value in Kotlin. Typesafe nulls transform them from a bad to a good idea. Arrow have even deprecated their Option
class in favour of null
.
If for some reason null
really doesn’t work, how about a java.util.Optional
? Or use a typealias of arrow.core.Either<Unit, T>
as suggested here: https://github.com/arrow-kt/arrow-core/issues/114#issuecomment-641211639 ?Rob Elliot
11/29/2021, 9:58 AMnull
(null safe dereferencing with ?.
, null defaulting with ?:
, null aware types, including generic types) makes nullable values massively easier to work with than any other option.
One thing to look out for is opportunities to use extension functions to simplify null handling:
Given:
val x: Grid? = TODO()
fun Grid.doSomeTransform(): String = TODO()
val result: String? = x?.doSomeTransform()
is often nicer than
fun doSomeTransform(grid: Grid): String = TODO()
val result: String? = x?.run { doSomeTransform(this) }