Skip to content

Instantly share code, notes, and snippets.

View tomaszperek's full-sized avatar

Tomasz Perek tomaszperek

View GitHub Profile
var x: String = null //error!
var x: String? = null // ok!
String x = null; // error!
String? x = null; // ok!
val l = b?.length() ?: -1;
// which is a shorthand notation for
val l: Int = if (b != null) b.length() else -1
String? x = "Some String"
Integer l = x.size // compilation error
Integer? l = x.size // compilation error
Integer? l = x?.size // this works.
var b: String? = "abc"
b.length() // error: variable 'b' can be null
b?.length() // ok - returns value of type Int?
data Maybe a = Nothing | Just a.
type 'a option = None | Some of 'a
sealed abstract class Option[+A] extends Product with Serializable {
...
}
final case class Some[+A](x: A) extends Option[A] {
def isEmpty = false
def get = x
}
case object None extends Option[Nothing] {
def isEmpty = true
//proper way to wrap calls to java apis
val map = new java.util.HashMap[String, String]()
map.put("key1", "value1")
val maybeValue1 = Option(map.get("key1")) //Some("value1")
val maybeValue2 = Option(map.get("key2")) //None
//equivalent of "if(x != null && condition(x))"
val optionX: Option[T] = Option(x)
optionX.exists(condition)
#simple example
=> (if nil "yes" "no")
"no"
# "elvis"
=> (or nil "Some value")
"Some value"
# if-let construct
=> (if-let [a-value (:a a-map)]