|
|
|
|
|
by wereHamster
3655 days ago
|
|
Ok, so there are instances, which throw exceptions, fine, we're in Java land after all, where anything can happen. But why is Tree[Nothing] more useful than Tree[Unit]? Both contain the same amount of information (both Nothing and Unit convey zero bits of information), but one throws an exception while the other is safe at runtime. |
|
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.