I had a problem with null data coming from one of the postgre db tables. In my situation, I have a column that is nullable which means it stores originally varchar data but has also null values for some rows. I read that column as Any data type inside Scala 2.
My first problem was using .toString function and I took Null Pointer Exception error of course. Then, I decided to cast that column to Option[String], but I couldn,t write pattern matching code.
Here is my trial:
val deneme = null
val myOption: Option[String] = deneme match {
case str: String => Option(str)
case null => None
}
As a result, I am taking that error:
<console>:26: error: pattern type is incompatible with expected type;
found : String
required: Null
case str: String => Option(str)
How can I come up with a solution for my case?
If know the root cause and solution, I will be really appreciated. Thanks in advance!
Null
is the universal subtype of reference types similarly to Nothing
, which is the universal subtype of all types.
So when you initialize a variable with null
, just declare the type
val deneme: String = null
Otherwise, the type of variable will be inferred Null
.
So happened here. Then all patterns were erroneously checked to conform Null
.