Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cheatsheet request: Scala #196

Open
rajit opened this issue Oct 31, 2017 · 0 comments
Open

Cheatsheet request: Scala #196

rajit opened this issue Oct 31, 2017 · 0 comments

Comments

@rajit
Copy link

rajit commented Oct 31, 2017

Perhaps things like:

Passing lambdas as values

Anonymous parameter syntax:

List(1, 2, 3).map(_ + 1) // = List(2, 3, 4)

Named parameter/expanded syntax, inferred type:

List(1, 2, 3).map(i => i + 1) // = List(2, 3, 4)

Named parameter, explicit type:

List(1, 2, 3).map((i: Int) => i + 1) // = List(2, 3, 4)

Receiving lambdas and using them

Single parameter:

def filter(list: List[Int], predicate: Int => Boolean): List[Int] = list match {
  case x :: xs if predicate(x) => x :: filter(xs, predicate)
  case Nil => Nil
}

Multiple parameters:

def combine(emptyValue: Int, list: List[Int], combiner: (Int, Int) => Int): Int = list match {
  case x :: y :: xs => combine(combiner(x, y) :: xs)
  case x :: Nil => x
  case Nil => emptyValue
}

Curried parameters:

def map(list: List[Int], adder: Int => Int => Int, amount: Int): List[Int] = list.map(adder(amount))
map(List(1, 2, 3), a => i => i + a, 10) // = List(11, 12, 13)

ADTs

sealed trait Message
case class Hello(name: String) extends Message
case object Goodbye extends Message

def log(msg: Message): Unit = msg match {
  case Hello(name) => println(s"Hello $name")
} // On compilation will warn of non-exhaustive match unless Goodbye is also matched

Type aliases

type MyType = String

def ping(msg: MyType) = ???

To change the kind of a type:

type ErrorOr[A] = Either[Throwable, A]
// Can be used where * -> * required

More ideas:

  • Type lambdas
  • Self types
  • Type classes
  • Context bounds
  • Higher-kinded types
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants