Skip to content

Instantly share code, notes, and snippets.

@matthandlersux
Created August 13, 2012 23:18
Show Gist options
  • Save matthandlersux/3344752 to your computer and use it in GitHub Desktop.
Save matthandlersux/3344752 to your computer and use it in GitHub Desktop.

Revisions

  1. matthandlersux created this gist Aug 13, 2012.
    50 changes: 50 additions & 0 deletions gistfile1.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    object Holder {
    var companions = Set[AnyRef]()

    def companionFor[M](m:M) = {
    companions.find {
    case found:M => true
    case _ => false
    }
    }
    }

    abstract class Model {
    def test = {
    Holder.companionFor(this)
    }
    }

    abstract trait CompanionTrait[M <: Model] { self:Model =>
    Holder.companions = Holder.companions ++ Set(self)
    }

    class T1 extends Model {

    }

    object T1 extends Model with CompanionTrait[T1] {

    }

    class T2 extends Model {

    }

    object T2 extends Model with CompanionTrait[T2] {

    }

    T1
    T2

    val x = new T1
    val y = new T2

    println("testing")
    assert(x.test == Some(T1))
    println("passed 1")
    assert(y.test != Some(T1))
    println("passed 2")
    assert(y.test == Some(T2))
    println("passed 3")