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
How to get the full month name?
val cal = Calendar.getInstance
val monthName = cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault)
println(monthName)
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)
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!"))
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)
Reference: 100+ Scala Code Examples
Top comments (0)