DEV Community

Discussion on: Functional Programming vs OOPS : Explain Like I'm Five

Collapse
 
thejhonny007 profile image
Jhonny • Edited

I know, I am late to the party, but functional programming and OOP are not exclusive. You can have things like classes, inheritance and polymorphism in pure functional code. Have a look at this Scala code:

abstract class SimpleList[+T] {
  def head: T
  def tail: SimpleList[T]
  def isEmpty: Boolean
  def length: Int

  def ::[S >: T] (newHead: S): SimpleList[S] = new ListNode(newHead, this)
}

class ListNode[T](hd: T, tl: SimpleList[T]) extends SimpleList[T] {
  override def head = hd
  override def tail = tl
  override def isEmpty = false
  override def length = 1 + tail.length
}

object EmptyList extends SimpleList[Nothing] {
  override def head = throw new NoSuchElementException
  override def tail = throw new NoSuchElementException
  override def isEmpty = true
  override def length: Int = 0
}

val squareNumbers = 1 :: 4 :: 9 :: 16 :: EmptyList
println(squareNumbers.length)
Enter fullscreen mode Exit fullscreen mode

We have a immutable list class that stores no mutable state, but uses all features of OO design. By definition of the pure functional paradigm this is also pure functional code.

It is a common misconception that fp and oop are exclusive.