Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kotlin Extensions in Scala
import scala.util.Try
implicit class KotlinLikeExtensions[A](a: => A) {
/**
* Produce a new value using current value
*/
def let[B](f: A => B): B = f(a)
/**
* Do something with current value and produce nothing
* Note: Cannot name it `apply` as in Kotlin because `apply` is special in Scala
*/
def run[U](f: A => U): Unit = f(a)
/**
* Do something with current value and return it as is
*/
def also[U](f: A => U): A = {
f(a)
a
}
/**
* Produce a new value using current value, catching exceptions in Try
* Note: works because value `a` is lazy (by-name parameter)
*/
def catching[B](f: A => B): Try[B] = Try(f(a))
/**
* Do something with current value and produce nothing, catching exceptions in Try
* Note: works because value `a` is lazy (by-name parameter)
*/
def runCatching[U](f: A => U): Try[Unit] = Try(f(a))
/**
* Access value only if it satisfies the predicate, lifting it to Option
*/
def takeIf(predicate: A => Boolean): Option[A] = if (predicate(a)) Some(a) else None
/**
* Access value only if it doesn't satisfy the predicate, lifting it to Option
*/
def takeUnless(predicate: A => Boolean): Option[A] = if (!predicate(a)) Some(a) else None
}
val hello = "hello"
// "hello world"
val helloWorld = hello.let { _ + " world" }
// Prints "hello world"
helloWorld.run { println }
// Prints "hello Akif" and returns "hello"
val hello2 = hello.also { h => println(s"$h Akif") }
// Failure(ArithmeticException)
(1 / 0).catching { _ * 2}
// Success(2)
(4 / 4).catching { _ * 2}
// Doesn't print since it fails
(1 / 0).runCatching { println }
// Prints "2"
(4 / 2).runCatching { println }
// Some(42)
println(42.takeIf(_ % 2 == 0))
// None
println(42.takeUnless(_ > 0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment