1

In the example below:

trait Writer[A] {
 def write(a: A): String
}

case class Person(name: String, age: Int)
case class Student(name: String, roll: Int)

object DefaultStringWriters {
//here is implicit object, when to use object here?

implicit object PersonNameWriter extends Writer[Person] {
  def write(person: Person) = person.name
 }

//here is implicit val, when to use val here?

implicit val studentNameWriter = new Writer[Student] {
  def write(student: Student) = student.name
 }
}

object WriterUtil {
 def stringify[A](data: A)(implicit writer: HtmlWriter[A]): String = {
  writer.write(data)
 }
}

#It works here with both.
WriterUtil.stringify(Person("john", "person@john.com"))
res0: String = john

WriterUtil.stringify(Person("student", "student@student.com"))
res1: String = student

When do we use implicit object or val in practical cases?

Haspemulator
  • 11,050
  • 9
  • 49
  • 76
PainPoints
  • 461
  • 8
  • 20

1 Answers1

1

Differences

  1. val is created during object initialization, and in the specified order. object is created lazily.

  2. object creates a new singleton type (e.g. PersonNameWriter.type) val creates either no type (as in this case), or a structural type.

  3. val can be overridden. object cannot.

  4. val can be assigned any expression, e.g. Foo() or new Foo. object must be a class definition, and is more limited in the ways it can reuse code, e.g. extends Foo.

If you don't care about any of these differences, then it doesn't matter which one you choose. In that case, I recommend val because it removes the need for any synchronization.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285