Created
April 8, 2020 10:35
-
-
Save makiftutuncu/5e77265fcc2e8369adca796a9d51c1c2 to your computer and use it in GitHub Desktop.
Kotlin Extensions in Scala
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
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