Hacker News new | ask | show | jobs
by duhace 3655 days ago
Tree[Nothing] is a subtype of all Tree[_] types. This is similar to Nil in scala, which is really a singleton implementation of List[Nothing] or None, which is a singleton implementation of Option[Nothing]. Unit does not have this property, it is just a subtype of AnyVal/Any.

Basically, Tree[Nothing] allows you to indicate that a Tree is empty via the type system while still allowing you to use that same type to build an actual tree from. If Nil was List[Unit] instead of List[Nothing], 1 :: Nil would be a compile time error instead of a List[Int].

Oh, and Unit does have an implementation in scala called "()", so if you had a Tree[Unit] you would not be able to tell if it was actually empty or not. You can see this in scala with () :: Nil. It produces a non-empty List[Unit]. Nothing has no such implementation. As for the exceptions, there's not much you can do wrt that. What should happen if you call head on an empty List? That's a straight-out error. headOption or a match block is the safe way to deal with lists if you don't want to have exceptions ever.