Search code examples
scalaself-type

Can I have multiple selftypes in Scala?


Can I have a class that can have two different self types in Scala? Or emulate it in some way?

object Hi {
    trait One {
        val num = 1
    }
    trait Two {
        val num = 2
    }
    class Test {
        this: One => {
            println(num)
        }
        this: Two => {
            println(num)
        }
    }
}

import Hi._
new Test with One
new Test with Two

Solution

  • Subtyping:

    scala> trait Num { def num: Int }
    defined trait Num
    
    scala> trait One extends Num { val num = 1 }
    defined trait One
    
    scala> trait Two extends Num { val num = 2 }
    defined trait Two
    
    scala> class Test { _: Num => def f() = println(num) }
    defined class Test
    
    scala> new Test with One
    res0: Test with One = $anon$1@389adf1d
    
    scala> .f()
    1
    

    Edit: Maybe that was a knee-jerk response and I should have said typeclasses.