Scala Nil equivalent for Set

Set.empty is that set; although you can’t get at it directly, it turns out that it is just a private object in the Set companion object (called, obviously enough, EmptySet). All that Set.empty does is return that set with a cast to the correct type. It is done this way, instead of with Nil, because … Read more

Map a Future for both Success and Failure

Edit 2017-09-18: As of Scala 2.12, there is a transform method that takes a Try[T] => Try[S]. So you can write val future = … // Future[T] val mapped = future.transform { case Success(_) => Success(“OK”) case Failure(_) => Success(“KO”) } For 2.11.x, the below still applies: AFAIK, you can’t do this directly with a … Read more

Scala transform list of tuples to a tuple of lists

You want unzip scala> List((1,”a”), (3, “b”), (4, “d”)).unzip res1: (List[Int], List[String]) = (List(1, 3, 4),List(a, b, d)) Similarly there is an unzip3 for List[Tuple3[A, B, C]], though anything of higher arity you’d have to implement yourself. scala> List((1,”a”, true), (3, “b”, false), (4, “d”, true)).unzip3 res2: (List[Int], List[String], List[Boolean]) = (List(1, 3, 4),List(a, b, … Read more

Scala default parameters and null

Pattern matching def aMethod(param: String = null) { val paramOrDefault = param match { case null => “asdf” case s => s } } Option (implicitly) def aMethod(param: String = null) { val paramOrDefault = Option(param).getOrElse(“asdf”) } Option (explicitly) def aMethod(param: Option[String] = None) { val paramOrDefault = param getOrElse “asdf” } The last approach … Read more

The tilde operator in Scala

Firstly, some meta-advice. Any time you’re wondering how the compiler expands some syntactic sugar, infers a type, or applies an implicit conversion, use scala -Xprint:typer -e <expr> to show you what happened. scala -Xprint:typer -e “val a = 2; ~a” … private[this] val a: Int = 2; private <stable> <accessor> def a: Int = $anon.this.a; … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)