I got a function like this. ``` override fun ...
# arrow
h
I got a function like this.
Copy code
override 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
Copy code
val carType = getCar("testname").fold( 
                        return Left({CarNotFound(it.message)}),
                        {it})
                )
m
Both parameters to
fold
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"))
.
s
I’m not understanding the 2nd snippet, calling the
getCar
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.
@Hexa What would you like the type of
carType
to be?
h
String
s
The id of the car. What if it was a left/error value. What should carType be then (type and value)?
m
and what does
loadCarAttributes
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.
s
@Hexa something like this?
Copy code
const val NO_ID = ""

val carType : String = getCar("testname")
    .fold(
        { NO_ID },
        { it }
    )
👍 1
h
yea @Mike
loadCarAttributes
returns an Either
thanks @streetsofboston that seems to work
s
Instead of
fold
here, you could use
getOrDefault
or
getOrElse
or
getOrHandle
instead (not sure which one works on an Either). Less typing
👍 1
h
I use getOrElse in the end then i just have a separate that if (cartype == NO_ID) return CarNotFound("car not found")
s
@Hexa But
carType
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…
h
@streetsofboston sorry I meant
Copy code
if (cartype.equals(NO_ID)) { return CarNotFound("car not found")}
s
And what does your code return if carType is not equal to NO_ID?