Skip to content

Instantly share code, notes, and snippets.

@pbassiner
Last active April 11, 2017 05:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbassiner/41c94ce57a3fd5da3a921587062ca2cb to your computer and use it in GitHub Desktop.
Save pbassiner/41c94ce57a3fd5da3a921587062ca2cb to your computer and use it in GitHub Desktop.
Blog Post - Why I Choose Scala: code snippets
case class User(name: String, email: String)
val x = List(1,2,3,4,5,6,7,8,9,10)
val evens = x.filter(a => a % 2 == 0) // List(2,4,6,8,10)
val anyEven = x.exists(a => a % 2 == 0) // true
x.foreach(a => println(a))
val doubles = x.map(x => x*2) // List(2,4,6,8,10,12,14,16,18,20)
val sum = x.foldLeft(0)((r,c) => r+c) // 55
val l = List(List(1,2), List(3,4))
val flat = l.flatten // List(1,2,3,4)
def double(i: Int): Int => Int = x => x*2
val doubles = List(1,2,3,4).map(double)
val f: Future[List[String]] = Future {
api.getCommits
}
f onComplete {
case Success(commits) => {
for (commit <- commits) {
println(commit)
}
}
case Failure(t) => println("Failure retrieving commits: " + t.getMessage)
}
def exists(userId: String): Boolean = ???
def getFromDb(userId: String): User = ???
def get(userId: String): Option[User] = {
if (exists(userId)) {
Some(getFromDb(userId))
} else {
None
}
}
def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "many"
}
def last[A](l: List[A]): A = l match {
case head :: Nil => head // Match lists with a single element
case _ :: tail => last(tail) // Match lists with more than an element
case _ => throw new NoSuchElementException // Anything else, an empty list in this case
}
sealed trait Expression
case class BooleanExpr(value: Boolean) extends Expression
case class AndExpr(left: Expression, right: Expression) extends Expression
case class OrExpr(left: Expression, right: Expression) extends Expression
case class NotExpr(expr: Expression) extends Expression
object ExpressionWriter extends App {
def write(expr: Expression): String = expr match {
case BooleanExpr(v) => s"$v"
case AndExpr(left, right) => s"(${write(left)} AND ${write(right)})"
case OrExpr(left, right) => s"(${write(left)} OR ${write(right)})"
case NotExpr(child) => s"(NOT ${write(child)})"
// No need for a default case, since trait being sealed guarantees exhaustiveness
}
println(
write(
AndExpr(
OrExpr(
BooleanExpr(true),
NotExpr(BooleanExpr(false))
),
OrExpr(
BooleanExpr(false),
AndExpr(
NotExpr(
BooleanExpr(true)
),
BooleanExpr(true)
)
)
)
)
)
}
val user: Option[User] = get("userId")
user match {
case Some(actualUser) => println("User: " + actualUser)
case None => println("User not found")
}
public class User implements Serializable {
private final String name;
private final String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public User withName(String name) {
return new User(name, email);
}
public User withEmail(String email) {
return new User(name, email);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
if (name != null ? !name.equals(user.name) : user.name != null) {
return false;
}
if (email != null ? !email.equals(user.email) : user.email != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = user != null ? user.hashCode() : 0;
result = 31 * result + (email != null ? email.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "User(" + name + "," + email + ")";
}
}
// define an abstract class for the iterator construct
abstract class AbsIterator {
type T;
def hasNext: Boolean;
def next: T;
}
// enrich iterators with an additional construct foreach
trait RichIterator extends AbsIterator {
def foreach(f: T => Unit): Unit =
while (hasNext) f(next);
}
// yet another iterator for Strings provides concrete
// implementations for all abstract methods inherited
class StringIterator(s: String) extends AbsIterator {
type T = Char;
private var i = 0;
def hasNext = i < s.length();
def next = { val x = s.charAt(i); i = i + 1; x }
}
// Usage: composition of StringIterator with RichIterator
object Test {
def main(args: Array[String]): Unit = {
class Iter extends StringIterator(args(0)) with RichIterator;
val iter = new Iter;
iter foreach System.out.println
}
}
// Tuple instantiation and value access
val userData = ("John", "john@scala.com", 30)
val name = userData._1
val email = userData._2
val age = userData._3
// Tuple instantiation and direct assignation to values
val (name, email, age) = ("John", "john@scala.com", 30)
// Tuple as return type
def get(): (String, String, Int) = ???
// Tuple as function parameter
def save(info: (String, String, Int)): Unit = ???
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment