Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle to read a column and cast to Option[String] from postgre db which has null and string values in Scala 2?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading