Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.annotation.tailrec
- def sum(l: Int*) : Int = {
- @tailrec
- def inner(xs: Seq[Int], acc: Int): Int = {
- xs match {
- case Seq() => acc
- case Seq(head ,tail@_*) => inner(tail, head + acc)
- }
- //if (xs.isEmpty) acc
- //inner(xs.tail, acc + xs.head)
- }
- def inner2(l: List[Int], acc: Int): Int = {
- l match {
- case Nil => acc
- case head :: tail => inner2(tail, head + acc)
- }
- }
- inner(l, 0)
- }
- sum(1, 2, 3)
- sum(List(1, 2, 3): _*)
- //**********************************************************
- val map = Map(1 -> "one", 2 -> "two")
- for ((num, str) <- map) {
- //unit
- }
- for ((num, str) <- map) yield {
- s"$num -> $str"
- }
- //один перенос строки -> ok
- 1+
- 2
- +3
- //fail, два переноса строки, интерпретируется как точка с запятой
- """
- 1+
- 2+
- 3
- """
- val set = Set(1, 2, 3)
- val list = List(1, 2, 3)
- for {
- elem <- set
- if elem % 2 != 0
- inc = elem + 1
- elem2 <- list
- } yield inc + elem2
- // *****************************************************************
- val a = Array(1, 2, 3)
- a(1) = 4
- a.update(1, 4)
- a.toSeq
- import scala.collection.JavaConverters._
- import java.util
- val javaCollection: util.List[Int] = Seq(1, 2, 3).asJava
- Seq(1,2,3).asJavaCollection
- javaCollection.asScala
- for (i <- javaCollection.asScala) yield i + 1
- import scala.collection.JavaConversions._
- for (i <- javaCollection) yield i + 1
- // ***************************************************************
- //function literals
- val inc1 = (x: Int) => x + 1
- val inc2: (Int => Int) = (x => x + 1)
- val inc3: (Int => Int) = _ + 1 //x$1 = x$1 + 1
- val inc4 = (_: Int) + 1
- def inc(x: Int) = x + 1
- val inc5: Int => Int = inc
- val inc6 = inc _
- val inc7: Int => Int = {
- case i => i + 1
- }
- val add1 = (x: Int, y: Int) => x + y
- val add2: (Int, Int) => Int = _ + _ // (x$1, x$2) => x$1 + x$2
- // _ - всегда новый параметр
- val add3: (Int, Int) => Int = (x, y) => x + y
- //high-order functions
- def map(list: List[Int], map: Int => Int): List[Int] = {
- for (elem <- list) yield map(elem)
- }
- map(List(1, 2, 3), inc3)
- map(List(1, 2, 3), x => x * 2)
- // **************************************************************
- val list1 = List(1, 2, 3)
- list1.map(_ + 1)
- list1.filter(_ % 2 == 0)
- list1.flatMap(x => Seq.fill(10)(x)) // fill 10 раз элемент x
- List(List(1), List(2)).flatten
- List(1, 2, 3).flatten // не скомпилируется
- list1.flatMap(x => Seq.fill(x)(x))
- list1.map(x => Seq.fill(x)(x)).flatten
- List(1, 2, 3).foldLeft(0)(_ + _) // последовательные скобки нужны для вывода типов
- //вторая скобка уже знает о типе параметра из первой скобки
- def foo(x: Int)(y: Int) = x + y
- val z: Int => Int = foo(1)
- def go(x: Int, y: Int) = x + y
- val z1: Int => Int = go(1, _)
- // *********************************************************
- //partial functions
- val partalFunction: PartialFunction[Int, Int] = {
- case x: Int if x % 2 == 0 => x / 2
- }
- partalFunction(2)
- partalFunction(3) //MatchError
- partalFunction.isDefinedAt(3)
- val inc7v2: Int => Int = {
- case i => i + 1
- }
- def isOdd(x: Int): Boolean = x % 2 == 0
- def isEven(x: Int): Boolean = x % 2 != 0
- list.find(_ == 2) //optional
- list.indexWhere(_ == 3)
- list.takeWhile(isEven)
- list.dropWhile(isEven)
- list.partition(isEven)
- list.groupBy(_ % 3)
- list.collect(partalFunction)
- list.filter(partalFunction.isDefinedAt).map(partalFunction)
- // ***********************************************************
- class B
- //primary constructor
- class C(x: Int) {
- val y = x + 1
- def foo: Unit = {
- print(x)
- }
- }
- new C(123)
- class A(x: Int) {
- def this(s: String) {
- //val x = ()... // так нельзя
- this(s.toInt) //всегда первая инструкция
- }
- val y = x + 1
- def foo: Unit = {
- print(x)
- }
- }
- class Base(x: Int)
- class D(x: Int) extends Base(x + 1) {
- }
- class E extends Base(1) {}
- new E
- def foo() = 1
- def foo1 = 1
- foo()
- foo
- //foo1() // нельзя
- foo1 // скобок нет - нет side-effects
- trait BaseTrait {
- def foo = 1
- val y: Int = 1
- var z: Int = 3
- }
- //отличия от класса - 1) нет конструктора 2) вызовы super (линеаризация и прочие прелести)
- //First, a trait cannot have any “class” parameters, i.e., parameters passed to the primary constructor of a class. In other words, although you could define a class like this: class Point(x: Int, y: Int)
- //The other difference between classes and traits is that whereas in classes, super calls are statically bound, in traits, they are dynamically bound. If you write “super.toString” in a class, you know exactly which method implementation will be invoked. When you write the same thing in a trait, however, the method implementation to invoke for the super call is undefined when you define the trait.
- //есть множественное наследование трейтов
- class F extends Base(1) with BaseTrait with Traversable[Int] {}
- object A extends BaseTrait {
- override def foo = 1
- }
- A.foo
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement