Michael Böiers
12/10/2024, 9:23 AMgrid.getOrNull(y)?.getOrNull(x)
Wouldn't it be cool if Kotlin had a "safe array index" operator, for example like so:
grid?[y]?[x]
grid[y]?[x]?
Petr Sýkora
12/10/2024, 9:41 AMMichael Böiers
12/10/2024, 9:48 AMMichael Böiers
12/10/2024, 9:49 AMMichael de Kaste
12/10/2024, 9:53 AMgrid?[y]?[x]
is grid nullable or getting y nullable? 😉ephemient
12/10/2024, 10:07 AMoperator fun <T> List<List<T>>.get(y: Int, x: Int): T? = getOrNull(y)?.getOrNull(x)
and then write grid[y, x]
Michael Böiers
12/10/2024, 10:29 AMgrid[y]?[x]?
? That would be more consistent 🙂Michael Böiers
12/10/2024, 10:30 AMMichael de Kaste
12/10/2024, 2:09 PMMichael de Kaste
12/10/2024, 2:11 PMPetr Sýkora
12/10/2024, 2:45 PMephemient
12/10/2024, 2:46 PMephemient
12/10/2024, 2:51 PMPetr Sýkora
12/10/2024, 2:58 PMMichael Böiers
12/10/2024, 3:00 PMephemient
12/10/2024, 3:33 PM.getNotNull
and if you think that's too long to type you can always alias it
import kotlin.collections.getOrNull as ʔ
listOf(1, 2, 3).ʔ(4)
ephemient
12/10/2024, 3:36 PMgrid[y]?[x]?.toString()
would be ambiguous between
grid[y]?[x] ?.toString()
and
grid[y]?[x]? .toString()
Neil Banman
12/10/2024, 3:50 PMtodd.ginsberg
12/10/2024, 5:24 PMcontains
operator and check that points are on the grid (point in grid
) before I call the get(point)
operator which doesn’t do any error checking (this[point.y][point.x]
). It works for me to do the bounds checking rather than returning a nullable type from get.
If this weren’t for Advent of Code, I would probably consider writing these with more safety in mind.Neil Banman
12/10/2024, 7:56 PMMichael Böiers
12/10/2024, 8:08 PMNeil Banman
12/10/2024, 8:37 PMMichael Böiers
12/10/2024, 8:42 PMgenerateSequence(::readLn).toList()
🙂