Pre SIP Introduce extension objects and lazy vals

Extension val and objects.

These are like extension methods except they are objects and vals instead.

Currently I need to write this which is not quite the same:

object MyService {
  object Live {
    val member = ()
  }
}

trait LayerCompanion {
  def member: Unit
}

extension (c: MyService.type) {
  def InMemory = new LayerCompanion {
    val member = ()
  }
}

object AccessTest {
  val x = MyService.Live.member
  val y = MyService.InMemory.member
}

I want to be able to write this instead:

object MyService {
  object Live {
    val member = ()
  }
}

extension (c: MyService.type) {
  object InMemory {
    val member = ()
  }
}

object AccessTest {
  val x = MyService.Live.member
  val y = MyService.InMemory.member
}

Also being able to do this with non companion objects would be nice too:


trait Trait

extension (c: Trait) {
  object InMemory {
    val member = ()
  }
}

object AccessTest {
  val t = new Trait {}
  val x = t.InMemory.member
}

For vals, we would require them to be lazy.

Implementation can be done by using WeakHashMap to keep extension objects and vals alive as long as the parent is alive.

2 Likes