DEV Community

Cover image for Useful Scala Code Snippets
SUDHIR SHARMA
SUDHIR SHARMA

Posted on

2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay