Code snippets used in blog post "Why I Choose Scala": https://pbassiner.github.io/blog/why_i_choose_scala.html
-
-
Save pbassiner/41c94ce57a3fd5da3a921587062ca2cb to your computer and use it in GitHub Desktop.
Blog Post - Why I Choose Scala: code snippets
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
case class User(name: String, email: String) |
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
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) |
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
def double(i: Int): Int => Int = x => x*2 | |
val doubles = List(1,2,3,4).map(double) |
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
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) | |
} |
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
def exists(userId: String): Boolean = ??? | |
def getFromDb(userId: String): User = ??? | |
def get(userId: String): Option[User] = { | |
if (exists(userId)) { | |
Some(getFromDb(userId)) | |
} else { | |
None | |
} | |
} |
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
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 | |
} |
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
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) | |
) | |
) | |
) | |
) | |
) | |
} |
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
val user: Option[User] = get("userId") | |
user match { | |
case Some(actualUser) => println("User: " + actualUser) | |
case None => println("User not found") | |
} |
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
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 + ")"; | |
} | |
} |
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
// 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 | |
} | |
} |
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
// 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