Сообщения

Сообщения за сентябрь, 2019

Scala tasks and questions - solutions and explanations

#1. Why method generates an error at compile time : Error here because the expression is expanding into SOMETHING match { case xs :Seq[Int] if xs.isEmpty => 0 case xs :Seq[Int] if xs.nonEmpty => xs.head + recursiveSum(xs.tail: _*) } and scala compiler doesn't know what is SOMETHING and his type. You think that it is xs : Int* parameter, but why. Functions definition can be like this def recursiveSum(a :Int,s :String, xs :Int*) :Int = { We can solve this by explicitly adding the parameter in the patter match, like this ( inside {} we use xs but it can be any name, it's not referred to internal parameter xs. ) def recursiveSum(xs :Int*) :Int = { xs match { case xs if xs.isEmpty => 0 case xs if xs.nonEmpty => xs.head + recursiveSum(xs.tail: _*) } } recursiveSum((1 to 5): _ *) result : 15 Also, we can do it without pattern matching, with IF val g: (Seq[Int]) => Int = si => { if (si.isEmpty) 0 else si.head + g(si.tail

Scala tasks and questions

In this topic, I will collect different questions and small tasks of Scala. Solutions or explanations will be on any page. All related by # - numbers. #1. Why method generates an error at compile time: error: missing parameter type for expanded function <console>:11: error: missing parameter type for expanded function The argument types of an anonymous function must be fully known. (SLS 8.5) Expected type was: Int        def recursiveSum(xs :Int*) :Int = {                                                               ^ For example, you write a method like this, to calculate sum recursively. def recursiveSum(xs :Int*) :Int = { case xs :Seq[Int] if xs.isEmpty => 0 case xs :Seq[Int] if xs.nonEmpty => xs.head + recursiveSum(xs.tail: _*) } #2. How to make a chain of PartialFunctions, manually and with fold, and use it to filter data.      And the short explanation about P.F. and their methods. val resultSeqPers :Seq[Person] = sourceSeqPers collect Co