Yogesh Chettiar
Yogesh Chettiar

Reputation: 51

Is there any reason to use classes vs object at all in Scala?

Just a precursor, I'm coming from a Java background and am fairly new to Scala. As I develop more in Scala and try to become more FP oriented, I realize I can make almost all of my code: functions (and even methods?) contained in Objects (with a sprinkling of case classes where needed). In that case - is there any use at all for regular classes?

Upvotes: 2

Views: 304

Answers (1)

simpadjo
simpadjo

Reputation: 4017

//traits (interfaces) without implementation are perfectly valid from FP standpoint
//it's just a bag of named functions
trait A {
  def foo(s: String): Int
}

//Ok, you can implement a trait without declaring a class
object Obj extends A {
  override def foo(s: String): Int = s.length
}

//But if you want your function to be parametrized then classes are useful
//You can think of classes as partially aplied functions in FP sense 
class Clz(param: String) extends A {
  override def foo(s: String): Int = (param + s).length
}

Upvotes: 3

Related Questions