I'm a seasoned Python developer and I have to learn Scala for my new job. I had a great time practicing Python with CodeWars and decided to try with Scala as well, but there's just something that I can't understand...
Bellow I have a partial solution to an exercise, you can find it here https://www.codewars.com/kata/5c8bfa44b9d1192e1ebd3d15/train/scala
object SheepAdvisor {
def warnTheSheepCheck(queue: Array[String]): String =
// println(queue)
if (queue.last == "wolf") {
"Pls go away and stop eating my sheep"
} else {
s"Oi! Sheep! You are about to be eaten by a wolf!"
}
}
What I don't understand is, why can't I just print the input? If I uncomment the print statement the entire code breaks. It just doesn't make sense to me.
The error:
src/main/scala/solution.scala:4: error: type mismatch;
found : Unit
required: String
println(queue)
^
src/main/scala/solution.scala:5: error: not found: value queue
if (queue.last == "wolf") {
I'm really used to just attack a problem by small parts, usually printing stuff to verify that I'm on the right track. Is it some sort of paradigm shift with Scala that I just don't know about?
Any Scala resources focused on people coming from Python would be very much appreciated!
CodePudding user response:
For Scala 2 (available on Codewars) you need to wrap the whole function body in curly brackets otherwise compiler treats warnTheSheepCheck
as invocation of println
which returns Unit
:
object SheepAdvisor {
def warnTheSheepCheck(queue: Array[String]): String = { // here
println(queue)
if (queue.last == "wolf") {
"Pls go away and stop eating my sheep"
} else {
s"Oi! Sheep! You are about to be eaten by a wolf!"
}
} // and here
}
Scala 3 has optional braces feature which allows to omit braces in this case.