Last active
August 29, 2015 14:18
-
-
Save Jacoby6000/4f11b6bac0212df22772 to your computer and use it in GitHub Desktop.
Unitype scala! woo!
This file contains hidden or 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
object Unitype { | |
implicit def objectToBool(obj: AnyRef): Boolean = obj != null | |
implicit def noneToBool(none: Option[Nothing]): Boolean = false | |
implicit def optToBool[T](opt: Option[T]): Boolean = opt.isDefined | |
trait Unityper[To, From] { | |
def convert: To | |
} | |
implicit class StrToBoolUnityper(string: String) extends Unityper[Boolean, String] { | |
def convert = string != "" && string != "0" && string != null | |
} | |
implicit class NumToBoolUnityper(num: Int) extends Unityper[Boolean, Int] { | |
def convert = num != 0 | |
} | |
implicit class BoolToNumUnityper(bool: Boolean) extends Unityper[Int, Boolean] { | |
def convert = if(bool) 1 else 0 | |
} | |
implicit class BoolUnwrapper(opt: Option[Boolean]) extends Unityper[Boolean, Option[Boolean]] { | |
def convert: Boolean = opt.getOrElse(false) | |
} | |
implicit class StringUnwrapper(opt: Option[String]) extends Unityper[String, Option[String]] { | |
def convert: String = opt.getOrElse("") | |
} | |
implicit class OptionUnwrapper[T](obj: Option[T]) extends Unityper[AnyRef, Option[T]] { | |
def convert: T = obj.get | |
} | |
implicit class OptionWrapper[T](obj: T) extends Unityper[AnyRef, Option[T]] { | |
def convert: Option[T] = if(obj == null) None else Some(obj) | |
} | |
implicit class OptionAnyValUnityper(opt: Option[AnyVal]) extends Unityper[AnyVal, Option[AnyVal]] { | |
def convert: AnyVal = opt.getOrElse(0) | |
} | |
implicit class NumOptionToBoolUnityper(opt: Option[Int]) extends Unityper[Boolean, Option[Int]] { | |
def convert = opt.isDefined && opt.get != 0 | |
} | |
implicit class BoolToIntOptionUnityper(bool: Boolean) extends Unityper[Option[Int], Boolean] { | |
def convert = if(bool) Some(1) else None | |
} | |
implicit def convert[T,U](t: T)(implicit unityperTrait: Unityper[U,T]): U = unityperTrait.convert | |
implicit class UnityperEq[T](obj: T) { | |
def ===(thing: T) = obj == thing | |
def !==(thing: T) = obj != thing | |
} | |
} | |
import Unitype._ | |
5 === false | |
//Some(0) === false | |
false === None | |
true === None | |
true === Some(1) | |
true === Some(0) | |
false === Some(0) | |
Some("what") === false |
It's not yet complete! Please contribute! We may yet convert the javascripters, haskellers, phpers, all unitypers! Also improve (make worse) if you can!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You are a bad person and you should feel bad