DEV Community

Cover image for Useful Scala Code Snippets
SUDHIR SHARMA
SUDHIR SHARMA

Posted on

Useful Scala Code Snippets

Scala is a strong statically typed general-purpose programming language which supports both object-oriented programming and functional programming.
In this article, I am writing some of the code snippets, which are useful in Scala programming language.

Swap two numbers without using third variable

num1 = num1 + num2
num2 = num1 - num2
num1 = num1 - num2
Enter fullscreen mode Exit fullscreen mode

How to get the full month name?

val cal = Calendar.getInstance
val monthName = cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault)
println(monthName)
Enter fullscreen mode Exit fullscreen mode

How to append varargs parameters to an ArrayBuffer?

val arrBuf = ArrayBuffer[String]()

// Adding one element
arrBuf += "New Delhi"

// Creating a method with a varargs parameter
def appendMultipleVarArgs(strings: ArrayBuffer[String], varArguments: String*): Unit = 
    arrBuf.appendAll(varArguments)

// Adding multiple varargs parameters
appendMultipleVarArgs(arrBuf, "Mumbai", "Bhopal")

// Printing elements
println(arrBuf)
Enter fullscreen mode Exit fullscreen mode

Script to convert strings to uppercase using object

object ConvertUpper {
 def upperfun(strings: String*) = strings.map(_.toUpperCase())
}
println(ConvertUpper.upperfun("Hello", "Hello, world!", "How are you?", "Bye!"))
Enter fullscreen mode Exit fullscreen mode

How to transform an array to a string using mkString?

val arr = Array(10,20,30)

var result = arr.mkString
println(result)

result = arr.mkString(",")
println(result)

result = arr.mkString(" ")
println(result)

result = arr.mkString("(", ",", ")")
println(result)
Enter fullscreen mode Exit fullscreen mode

Reference: 100+ Scala Code Examples

Top comments (0)