Hexa
03/15/2019, 3:30 PMoverride fun getCar(name: String): Either<CarNotFound, String?> {
val carAttributes = loadCarAttributes(name)
return when (carAttributes) {
is Either.Right -> {
return Right(carAttributes.b.attributes["carId"])
}
is Either.Left -> {
Left(CarNotFound("car not found"))
}
}
}
When I call that function I want to access the values so that if the value is Left then I just return CarNotFound to the client.
Else I use the value on the Right (which is just a string) to do further processing. I tried something like this but it didnt't work
val carType = getCar("testname").fold(
return Left({CarNotFound(it.message)}),
{it})
)Mike
03/15/2019, 3:39 PMfold are Lambdas, so that’s one thing.
Also why are you doing a fold when getCar will already return a Left(CarNotFound("car not found")).streetsofboston
03/15/2019, 3:39 PMgetCar method.
The first param of fold is a return expression, meaning that it returns a value of type Nothing. After the return a Left value holding a lambda is created.
The 2nd parameter of fold returns just the String.streetsofboston
03/15/2019, 3:41 PMcarType to be?Hexa
03/15/2019, 3:41 PMstreetsofboston
03/15/2019, 3:41 PMMike
03/15/2019, 3:42 PMloadCarAttributes return? It appears it returns an Either, so perhaps you need to fold it or loadCarAttributes should return an Option, in which case that code could use toEither() on the response.
I think more code/context is required to correctly analyze this, and suggest improvements.streetsofboston
03/15/2019, 3:44 PMconst val NO_ID = ""
val carType : String = getCar("testname")
.fold(
{ NO_ID },
{ it }
)Hexa
03/15/2019, 3:45 PMloadCarAttributes returns an EitherHexa
03/15/2019, 3:56 PMstreetsofboston
03/15/2019, 4:03 PMfold here, you could use getOrDefault or getOrElse or getOrHandle instead (not sure which one works on an Either). Less typingHexa
03/15/2019, 4:26 PMstreetsofboston
03/15/2019, 5:41 PMcarType is a String. CarNotFound is not a String.
Your getCar already handles this by returning an Either of CarNotFound and String….. I’m not sure what the code that calls getCar(...) should return then…Hexa
03/15/2019, 5:42 PMif (cartype.equals(NO_ID)) { return CarNotFound("car not found")}streetsofboston
03/15/2019, 5:50 PM