Skip to content

Instantly share code, notes, and snippets.

View awelm's full-sized avatar
🎯
Focusing

Akila Welihinda awelm

🎯
Focusing
View GitHub Profile
// A case class in Scala is just a typed tuple
case class Person(name: String, title: String)
val person = Person("Joe Smith", "Mr")
val professors = Set("Joe Smith")
val greeting = person match {
case Person(name, "Dr") =>
// This block executes if person has the title "Dr"
s"Welcome Doctor $name"
// Note all variables declared with `val` are immutable
val opt = Some(5) // type: Option[Int], value: Some(5)
/*
* map lets you run a transformation function on the value possibly stored
* inside the Option. If map is called on an empty Option, then map will skip
* the transformation function and return None. The first map call below prints
* the stored value and then adds 2 to it. The second map call wraps the stored
* value inside another Option, which is why the return value has an extra
* Option layer. The third call always replaces the stored value with None.
viewerId = None
subscription = user.getSubscription()
if subscription:
premiumTier = subscription.getPremiumTier()
if premiumTier:
premiumId = premiumTier.getPremiumId()
if premiumId:
viewerId = premiumId
else:
val viewerId = user.getSubscriptionOpt // type: Option[Subscription]
.flatMap(_.getPremiumTierOpt) // type: Option[Tier]
.flatMap(_.getPremiumIdOpt) // type: Option[ID]
.getOrElse(user.getId()) // type: ID
// type: Future[String]
val stringFut = Future {
Thread.sleep(1000)
"Returned string"
}
/*
* You can call map() to register a synchronous operation
* to run once this Future completes successfully
*/
async def storeWords():
computedString = await computeString()
words = computedString.split(" ")
await persistWords(words)
asyncio.run(storeWords())
computeString.map(_.split(" ")).flatMap(persistWords)
// type: Try[Int], value: Success(6)
val toIntTry = Try {
"6".toInt
}
// type: Try[Int], value: Success(7)
val incrementedIntTry = toIntTry.map(_+1)
// type: Try[Double], value: Success(7.0)
val toDoubleTry = incrementedIntTry.flatMap { integer =>
try:
file = open("a.txt", 'rb')
except Exception:
try:
file = open("b.txt", 'rb')
except Exception:
pass
def openFileTry(name: String): Try[Source] = Try(Source.fromFile(name))
val fileTry = openFileTry("a.txt").getOrElse(openFileTry("b.txt"))