val ve def'in özelliğimi karıştırırken bazı başlatma garipliklerini görüyorum. Durum aşağıdaki örnekle özetlenebilir.Bir öznitelikte bir soyut değere bağlı olarak bir null alma
Soyut bir alan sağlayan bir özellik var, onu çocuk sınıflarında uygulanması gereken fruit
diyelim. beklendiği gibi
scala> class FruitTreeDescriptor(fruit: String) {
| def describe = s"This tree has loads of ${fruit}s"
| }
defined class FruitTreeDescriptor
scala> trait FruitTree {
| def fruit: String
| val descriptor = new FruitTreeDescriptor(fruit)
| }
defined trait FruitTree
bir def
ile fruit
basan, işlerin: Aynı zamanda bir val bu alanı kullanır ...
scala> object AppleTree extends FruitTree {
| def fruit = "apple"
| }
defined object AppleTree
scala> AppleTree.descriptor.describe
res1: String = This tree has loads of apples
Ancak ben val
kullanarak fruit
geçersiz kılarsanız,
scala> object BananaTree extends FruitTree {
| val fruit = "banana"
| }
defined object BananaTree
scala> BananaTree.descriptor.describe
res2: String = This tree has loads of nulls
Neler oluyor burda?