A quick question around Smart Casts. I would love ...
# announcements
n
A quick question around Smart Casts. I would love to use
require()
(and
check()
in other cases) as a smart cast to implement a guard like this:
Copy code
fun String.toGeoLineString(): LineString {
  val geometry = readGeometryFromString(this)
  require(geometry is LineString) { "Wrong geometry type in string" }
  return geometry
}
but this obviously does not work, because checking the type in require is not enough for smart casting to work so I need to do
Copy code
fun String.toGeoLineString(): LineString {
  val geometry = readGeometryFromString(this)
  if (geometry !is LineString) { 
    throw IllegalArgumentException("Wrong geometry type") 
  }
  return geometry
}
or even crazier
Copy code
fun String.toGeoLineString(): LineString {
  val geometry = readGeometryFromString(this)
  geometry as? LineString ?: throw IllegalArgumentException("Wrong geometry type")
  return geometry
}
Since require and check are library functions there is probably no way to use them for smart casting, right? Any other ideas?