What to call a car owner?

Report a typo

We have the following case classes in our service domain:

case class Owner(name: String, phone: String)  

case class Car(name: String, isCrashed: Boolean, owner: Maybe[Owner])

We need a function that will retrieve the owner's phone number if the car data has been presented and the car has not been broken. We have written it, but our specific data type Maybe must have several methods implemented to make this code work:

def getOwnerPhone(maybeCar: Maybe[Car]): Maybe[String] =
  for 
    car <- maybeCar if !car.isCrashed
    owner <- car.owner
  yield owner.phone

Complete the Maybe data structure.

Sample Input 1:

name hasAccident contactName contactPhone
BMW  false       Alice       673(92)189-66-38

Sample Output 1:

673(92)189-66-38
Write a program in Scala 3
sealed trait Maybe[+A] {
def map[B](f: A => B): Maybe[B]
def flatMap[B](f: A => Maybe[B]): Maybe[B]
def withFilter(f: A => Boolean): Maybe[A]
}

case object Empty extends Maybe[Nothing] {
def map[B](f: Nothing => B): Maybe[B] = this
def flatMap[B](f: Nothing => Maybe[B]): Maybe[B] = ???
def withFilter(f: Nothing => Boolean): Maybe[Nothing] = ???
}

case class Value[A](value: A) extends Maybe[A] {
def map[B](f: A => B): Maybe[B] = Value(f(value))
def flatMap[B](f: A => Maybe[B]): Maybe[B] = ???
def withFilter(f: A => Boolean): Maybe[A] = ???
}
___

Create a free account to access the full topic