Created
September 6, 2014 14:33
-
-
Save ElectricCoffee/4f5fab55b4e2073b0d0d to your computer and use it in GitHub Desktop.
Got a little miffed by the fact that str.toInt threw an exception if a non-convertible string was encountered (a-la "hello".toInt), so I figured it would make more sense if it returned an option instead, using this library you can do this: "hello".opt.toInt which would return None, saving you a tedious try/catch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.wausoft.extensions | |
object SafeString { | |
class StrOps(input: String) { | |
private def toOption[A](in: => A) = try { | |
Some(in) | |
} catch { | |
case _: Throwable => None | |
} | |
def toInt: Option[Int] = toOption(input.toInt) | |
def toFloat: Option[Float] = toOption(input.toFloat) | |
def toDouble: Option[Double] = toOption(input.toDouble) | |
def toLong: Option[Long] = toOption(input.toLong) | |
} | |
implicit class RichString(val left: String) extends AnyVal { | |
def opt: StrOps = new StrOps(left) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment