Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set multiple typed variables to null

Tags:

scala

I have a bunch of lazy val Strings that I'd like to set all at once, and there is a certain case where they should be set to null (I know this is not the Scala way, but it is for Java compatibility)

Normally I can set the variables in the typical multi-assignment manner:

scala> val (a: String, b: String) = ("a", "b")
a: String = a
b: String = b

As soon as I add a null into the mix, everything goes haywire:

scala> val (a: String, b: String) = (null, null)
<console>:12: error: pattern type is incompatible with expected type;
 found   : String
 required: Null
       val (a: String, b: String) = (null, null)
               ^
<console>:12: error: pattern type is incompatible with expected type;
 found   : String
 required: Null
       val (a: String, b: String) = (null, null)

Is there a way to set multiple typed variables to null?

I'm guessing this has something to do with the pattern matching involved in setting multiple variables since this is just fine:

scala> val a: String = null
a: String = null
like image 372
kjb Avatar asked Dec 13 '25 22:12

kjb


2 Answers

There is a puzzler for the pattern match:

http://scalapuzzlers.com/#pzzlr-035

Did no one offer the obvious?

scala> val a,b,c: String = null
a: String = null
b: String = null
c: String = null

AIA if I'm missing something.

The difference is specified in 4.1.

like image 61
som-snytt Avatar answered Dec 15 '25 22:12

som-snytt


This syntax seems to work.

scala> val (a, b) = (null, null): Tuple2[String,String]
a: String = null
b: String = null
like image 24
Tim Avatar answered Dec 15 '25 23:12

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!