50 Scala Coding Exercises with Solutions
50 Scala Coding Exercises with Solutions
Scala is a powerful programming language that combines object-oriented and functional programming. Practicing coding problems is one of the best ways to master Scala syntax, collections, pattern matching, and functional concepts. Below are 50 Scala coding exercises with short solutions to help you strengthen your skills from beginner to advanced level.
println("Hello, World!")
val a = 10
val b = 20
println(a + b)
def isEven(n: Int) = n % 2 == 0
val a = 5
val b = 10
val swapped = (b, a)
def max(a: Int, b: Int) = if (a > b) a else b
def factorial(n: Int): Int = if (n == 0) 1 else n * factorial(n - 1)
def fibonacci(n: Int): Int = if (n <= 1) n else fibonacci(n-1) + fibonacci(n-2)
"Scala".reverse
def countVowels(s: String) = s.count("aeiou".contains(_))
def isPalindrome(s: String) = s == s.reverse
List(1,2,3).sum
List(4,7,1,9).max
List(3,1,4).sorted
"scala".toUpperCase
scala.util.Random.nextInt(100)
List(1,2,2,3).distinct
def isPrime(n: Int) = (2 until n).forall(n % _ != 0)
List(1,2,3,4).filter(_ % 2 == 0)
List(1,2,3).map(x => x * x)
List(1,2,3).reduce(_ + _)
List(List(1,2), List(3,4)).flatten
"Scala is powerful".split(" ").length
List(4,7,1,9).sorted.reverse(1)
List(1,2) ++ List(3,4)
List(1,2,2,3).toSet
List(1,2,2,3).groupBy(identity).mapValues(_.size)
List(1,2,3).reverse
def isAnagram(a: String, b: String) = a.sorted == b.sorted
def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
def lcm(a: Int, b: Int) = (a * b) / gcd(a, b)
List(1,2,3,4).take(2)
List(1,2,3,4).drop(2)
(Implement using digit power sum logic)
List(1,2,3).length
List(1,2,3).mkString(",")
val value: Option[Int] = Some(5)
value.getOrElse(0)
def matchTest(x: Any) = x match {
case 1 => "one"
case _ => "other"
}
case class Person(name: String, age: Int)
(Practice using List vs ArrayBuffer)
trait Animal { def speak(): String }
class Dog extends Animal { def speak() = "Woof" }
def applyFunc(f: Int => Int, x: Int) = f(x)
List(1,2,3).foldLeft(0)(_ + _)
(Use recursion over List)
import scala.concurrent.Future
try { 10/0 } catch { case e: Exception => println("Error") }
(Use scala.io.Source.fromFile)
implicit val multiplier = 2
val pf: PartialFunction[Int, String] = { case 1 => "one" }
class Demo
object Demo
def calculator(a: Int, b: Int, op: String) = op match {
case "+" => a + b
case "-" => a - b
case "*" => a * b
case "/" => a / b
}
Practicing these 50 Scala coding exercises with solutions will help you strengthen your understanding of Scala fundamentals, collections, recursion, functional programming, and advanced features. Regular practice combined with real-world project implementation will significantly improve your Scala programming confidence and problem-solving ability.