2016-02-25 1 views
0

Est-il possible d'initialiser un attribut dans un trait de gabarit joint? Quelque chose de similaire aux initialiseurs précoces. Par exemple:Initialisation d'un attribut de trait lors de l'utilisation du gabarit de gâteau

object CakePatternInit { 

    trait A { 
    var prop: String = null 
    } 

    trait A1 extends A 

    trait B { 
    this: A => 
    println(prop.toUpperCase) // I'd like here prop to be initialized already with "abc" 
    } 

    def main(args: Array[String]) { 

    val b = new B with A1 
    // how do I initialize prop here? 
    // can I write something like this: 
    // val b = new B with { prop = "abc" } A1 
    } 
} 
+0

Comment à ce sujet: http://stackoverflow.com/questions/35359022/scala-trait-member-initialization-use-traits-to-modify-class-member/35359899#35359899 –

Répondre

1
trait A { 
    def prop: String 
    } 

    trait A1 extends A 

    trait B { 
    this: A => 
    println(prop.toUpperCase) // I'd like here prop to be initialized already with "abc" 
    } 

    val t = new B with A1 { def prop = "Hello"} 
    > HELLO 
    > t.prop 
    res22: String = Hello 

Déclarez votre prop comme méthode, car scala ne peut pas remplacer var « s

Il y a un article qui peut vous aider: cake pattern

+0

plus d'infos il re: http://docs.scala-lang.org/tutorials/FAQ/initialization-order.html – Adrian