Interview :: Scala
In Scala, the array is a combination of mutable values. It is an index based data structure. It starts from 0 index to n-1 where n is the length of the array.
Scala arrays can be generic. It means, you can have an Array[T], where T is a type parameter or abstract type. Scala arrays are compatible with Scala sequences - you can pass an Array[T] where a Seq[T] is required. Scala arrays also support all the sequence operations.
Example
In Scala, the string is a combination of characters, or we can say it is a sequence of characters. It is index-based data structure and uses a linear approach to store data into memory. The string is immutable in Scala like java.
Example
Starting in Scala 2.10.0, Scala offers a new mechanism to create strings from your data. It is called string interpolation. String interpolation allows users to embed variable references directly in processed string literals. Scala provides three string interpolation methods: s, f and raw.
Example
The s method of string interpolation allows us to pass a variable in the string object. You don't need to use the + operator to format your output string. This variable is evaluated by the compiler and replaced by value.
Example
The f method is used to format your string output. It is like printf function of C language which is used to produce formatted output. You can pass your variables of any type in the print function.
Example
The raw method of string interpolation is used to produce a raw string. It does not interpret special char present in the string.
Example
Exception handling is a mechanism which is used to handle abnormal conditions. You can also avoid termination of your program unexpectedly.
Scala makes "checked vs. unchecked" very simple. It doesn't have checked exceptions. All exceptions are unchecked in Scala, even SQLException, and IOException.
Example
Scala provides try and catch block to handle the exception. The try block is used to enclose suspect code. The catch block is used to handle exception occurred in the try block. You can have any number of the try-catch block in your program according to need.
Example
In this example, we have two cases in our catch handler. The first case will handle only arithmetic type exception. The second case has a Throwable class which is a super-class in the exception hierarchy. The second case can handle any type of exception in your program. Sometimes when you don't know about the type of exception, you can use super-class.
The finally block is used to release resources during exception. Resources may be a file, network connection, database connection, etc. The finally block executes guaranteed.
Example
You can throw an exception explicitly in your code. Scala provides throw keyword to throw an exception. The throw keyword mainly used to throw a custom exception.