neil
neil

Reputation: 169

Convert Option[String] to Map[String,trait] in SCALA

I am new to Scala and searched for the same as to how can we change from Option[String] to a Map[String,trait] but could not find much .

The thing is I have a field of type Option[String] and I have to pass that value to a case class which takes input as a Map[String,User Defined trait].

That's what I want to know as to how can I convert the value of Option[String] to Map[]

Can we use Option.fold in this?

Could you please guide me further on this.

TIA

Upvotes: 0

Views: 1276

Answers (2)

Leo C
Leo C

Reputation: 22439

Consider using toMap as shown in the following example:

trait UDTrait[A] {
  def len(s: A): Int
}

case class MyClass(m: Map[String, UDTrait[String]])

def myOptionToMap(opt: Option[String]): Map[String, UDTrait[String]] =
  opt.map((_, new UDTrait[String]{ def len(s: String) = s.length })).toMap

MyClass(myOptionToMap(Some("a")))
// res1: MyClass = MyClass(Map(a -> $anonfun$myOptionToMap$1$$anon$1@10aabada))

MyClass(myOptionToMap(None))
// res2: MyClass = MyClass(Map())

Alternatively, you can use fold, as follows:

def myOptionToMap(opt: Option[String]): Map[String, UDTrait[String]] =
  opt.fold(Map.empty[String, UDTrait[String]])(s =>
    Map(s -> new UDTrait[String]{ def len(s: String) = s.length })
  )

Upvotes: 1

Bhargava Nandibhatla
Bhargava Nandibhatla

Reputation: 254

Option[ T ] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value.

A Map is an Iterable consisting of pairs of keys and values. If you want to construct a map with one key value pair from an option which is non-empty, you can do the following:

trait Foo

def convertNonEmptyOptionToMap(a:Some[String], t: Foo): Map[String, Foo] = Map(a.get -> t)

That said, I don't completely understand what you're trying to do. More context with examples would be helpful.

Upvotes: 0

Related Questions