[Noob] map getOrThrow(?)

I just wanted to do a quick:

map.getOrThrow(key, k => throw MyError(s"$k not found"))

but there doesn’t seem to be a similar method. I tried to get this to work:

map.get(key, => throw new MyError(""))

which failed to compile. I ended up with this:

private def getOrThrow(key: String) = mapByName.get(key) match { case Some(value) => value case None => throw MyError(s"key $key not found in $resource while initializing") }

but it feels ridiculously verbose. Any other thoughts?

PS: any hints on posting code welcome.

You can exploit the fact that the second argument of getOrElse is a by-name parameter like:

map.getOrElse(key, throw MyError(s"$key not found"))

This won’t throw the exception unless the key was not found.
BTW, it is usually better to represent those errors as values rather than throwing exceptions, so I would do something like:

map.get(key).toRight(left = MyError(s"$key not found"))
3 Likes

Which is why we always have these implicits in scope:

	implicit def option2RichOptionImplicit[V](o: Option[V]): Option2RichOption[V] = new Option2RichOption(o)
	class Option2RichOption[V](o: Option[V]) {
		def getOrThrowException(msg: => String): V = {
			o match {
				case Some(v) => v
				case None => throw new IllegalArgumentException(msg)
			}
		}
		def getOrThrow(t: => Throwable): V = {
			o match {
				case Some(v) => v
				case None => throw t
			}
		}
		def ifEmpty(func: => Unit): Option[V] = {
			if (o.isEmpty) {
				func
			}
			o
		}
		def mapIfEmpty[R](func: => R): Option[R] = {
			if (o.isEmpty) {
				Some(func)
			} else {
				None
			}
		}

		def ifNonEmpty(func: V => Unit): Option[V] = {
			o.foreach(func)
			o
		}
		def pass(func: Option[V] => Unit): Option[V] = {
			func(o)
			o
		}
	}
2 Likes

Thanks for that. I looked in the Option docs and couldn’t find them. It looks like I need to study the predefs.