Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.collection.mutable
- import scala.util.Random
- object Tasks {
- object EverythingIsExpression {
- val x = 123
- val y = if (x > 10) 1 else "string" // тип
- }
- EverythingIsExpression.y
- object FunctionAsValue {
- def sum(a: Int, b: Int, f: Int => Int): Int =
- if (a > b) 0 else f(a) + sum(a + 1, b, f)
- def sqr(n: Int) = n * n
- val sum1: Int = sum(-1, 2, sqr)
- val sum2: Int = sum(-1, 2, x => x)
- def mul(m: Int, n: Int) = m * n
- val sum3: Int = sum(-1, 2, mul(_, 12))
- }
- FunctionAsValue.sum1
- FunctionAsValue.sum2
- FunctionAsValue.sum3
- object ImmutabilityAndSideEffects {
- def getRandomNumberTimesX(x: Int) = x * Random.nextDouble()
- def getSqrtOfX(x: Int) = Math.sqrt(x)
- class MutableComplexNumber(var re: Double, var im: Double)
- /*case */class ComplexNumber(val re: Double, val im: Double)
- val mutVal = new MutableComplexNumber(12, 13)
- mutVal.re = 123
- val immutVal = new ComplexNumber(12, 13)
- val mutList = new mutable.MutableList[ComplexNumber]
- mutList += immutVal
- val immutList = List(immutVal, immutVal)
- // применение в жизни. предсказуемость. кэширование
- }
- ImmutabilityAndSideEffects.getRandomNumberTimesX(12)
- ImmutabilityAndSideEffects.getSqrtOfX(100)
- ImmutabilityAndSideEffects.mutList
- ImmutabilityAndSideEffects.immutList
- object CaseClasses {
- abstract class Try[T]
- case class Success[T](result: T) extends Try[T]
- case class Failure[T](e: Throwable) extends Try[T]
- object Try {
- def apply[T](operation: () => T): Try[T] = {
- try {
- Success(operation())
- } catch {
- case e: Throwable => Failure(e)
- }
- }
- }
- }
- CaseClasses.Try(() => 1/0)
- object ByNameParameter {
- abstract class Try[T]
- case class Success[T](result: T) extends Try[T]
- case class Failure[T](e: Throwable) extends Try[T]
- object Try {
- def apply[T](operation: => T): Try[T] = {
- try {
- Success(operation)
- } catch {
- case e: Throwable => Failure(e)
- }
- }
- }
- val try2 = Try(1/0)
- def sqr(n: => Int) = n * n
- def x = {
- println("getting x")
- 12
- }
- val squared = sqr(x)
- }
- ByNameParameter.try2
- ByNameParameter.squared
- object CollectionFunctions {
- case class Person(name: String, age: Int)
- val list = Seq(new Person("Matt", 12), new Person("Patt", 11))
- }
- CollectionFunctions.list.filter(p => p.name.charAt(0) == 'M')
- CollectionFunctions.list.foldLeft(0)((z,p) => z + p.age)
- object ForYield {
- import scala.util.Try
- val oddsSquares = for (x <- 1 to 15 if x % 2 == 1) yield x * x
- val anotherOddsSquares = (1 to 15)
- .withFilter { case (x) => x % 2 == 1}
- .map { case x => x * x }
- val tryResult = for (
- x <- Try(12);
- y <- Try(4 / x);
- z <- Try(throw new Exception)
- ) yield y / 0
- }
- ForYield.oddsSquares
- ForYield.anotherOddsSquares
- ForYield.tryResult
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement