0

I just started learning Scala and I am trying to solve a very simple exercise on HackerRank.

I get a number and a list as input and I want to print them N number of times.

This is the function I wrote:

def f(num:Int,arr:List[Int]):List[Int] = {
    arr.foreach((element:Int) => print((s"$element" + "\n") * num))
}

Error:

Solution.scala:3: error: type mismatch;
 found   : Unit
 required: List[Int]
    arr.foreach((element:Int) => println((s"$element" + "\n") * num))
               ^
one error found

If I run the same thing in my scala (v2.13) console, I get the expected output

pissall
  • 7,109
  • 2
  • 25
  • 45
  • 2
    Output (sent to StdOut) is not the same thing as a result returned from a method or function. `f()` is defined to return `List[Int]` but `foreach()` returns `Unit` so the code isn't in agreement. If all you need is the desired StdOut then redefine `f()` to return `Unit`. – jwvh Nov 01 '19 at 07:55
  • @jwvh Can you help me out with it? I tried to return `arr` again, but it still won't accept. here is a link to the [problem](https://www.hackerrank.com/challenges/fp-list-replication/problem) – pissall Nov 01 '19 at 08:02
  • 2
    @pissall This is something which is mostly common across languages. Your functions should return appropriate values. If you are having problem with this then I will advise you to read about Scala from a book such as https://underscore.io/books/essential-scala/ . – sarveshseri Nov 01 '19 at 08:07
  • @SarveshKumarSingh Thanks for the resource! I'm also trying to follow Martin Odersky's course on Coursera, but it all just bounces off my head. – pissall Nov 01 '19 at 08:08
  • Yes... because that course is more about `functional programming in Scala` and has almost nothing to do with `programming in Scala` or `understanding Scala`. This book starts from the fundamentals of Scala, then covers everything which you will learn in that course and goes well beyond that. – sarveshseri Nov 01 '19 at 08:11
  • 1
    @pissall; The [List Replication](https://www.hackerrank.com/challenges/fp-list-replication/problem) challenge at HackerRank has nothing to do with StdOut. So don't use `print()` or `println()` (or `foreach()` for that matter). You're supposed to create a new `List[Int]` with the required contents and return that from your method `f()`. – jwvh Nov 01 '19 at 08:22
  • 1
    Question for OP would be, are you trying to print the new list, or return a new List? You should clarify what you want to do first, and then try to find a solution. – SwiftMango Nov 01 '19 at 09:50
  • @texasbruce I have understood that I do not have to print anything here, rather I have to create a new list. My bad understanding the exact problem. I have picked up a book to learn Scala rather than just getting into solving challenges. I thought it wouln't be very difficult. Thanks everyone. – pissall Nov 01 '19 at 10:31

0 Answers0