3 ms·
I remembered another thing that Java users already know but surprised me in Scala in a bad way: null. I read a lot about Scala's type system in the week between
by philipkglass 10y ago
I remembered another thing that Java users already know but surprised me in Scala in a bad way: null. I read a lot about Scala's type system in the week between I was hired to write Scala and when I actually started writing code. Most of it was about how great Scala's type system was and how much safety it provided; the company even called itself Typesafe then. I read many paeans to the virtues of Scala's type system that would turn runtime errors into compile time errors, but they didn't highlight that it can't prevent that most common and annoying of Java runtime errors, the NullPointerException. Due to a lack of prominent mentions in the Scala docs and tutorials I read, I thought that Scala authors either didn't have to think about Java's Billion Dollar Mistake or that the compiler would guide them to safety before the code could blow up at runtime.
Maybe manually dealing with nulls is supposed to just be assumed by anyone using the JVM... But I'd used Jython a little in the past and I didn't have to explicitly deal with null-checking then. Jython converts null to None. In the absence of prominent warnings to the contrary I had thought that Scala would provide at least as much automatic safety as Python-on-JVM does.
- aianus 10y agoThe correct way to handle this in Scala is to wrap the possibly-null reference (which I assume you're getting as a return value from some Java library) in Option(), not manually checking for null.
- philipkglass 10y agoBy "manually checking" I mean that I have to use my own brainpower to notice places where null can leak in to code I'm writing; the compiler doesn't actually enforce the type safety I thought I had. I do use Option to handle sometimes-nulls after I notice them. EDIT: since Jython doesn't allow raw nulls to leak in from Java libraries, and Kotlin prevents accidental use of nullable values at compile time, it naively seems like Scala could prevent accidental null introduction despite living on the JVM. Or as a distant second-best, prominently warn about the perils of null whenever introducing its type system to beginners.
- yawaramin 10y agoAren't Jython `None` values essentially `null`s? But, Kotlin, Swift, and others are starting to get it right. Scala will follow suit--the plan is for 'Dotty', the next major version of the Scala compiler, to represent nullable types explicitly as `A | Null` (`A` or `Null`). Without that explicit type there will be no way for a type to hold `null`. Until that happens, in Scala we continue to work through in the presence of potential nulls by wrapping stuff that comes from Java APIs in `Option`s and never explicitly returning `null` from any Scala APIs.