Why do abstract variables require type annotations in scala?

When I have an abstract class with variables below

abstract class Book {

  val id : Int
  val name : String
  val book : Long

}

Declaring them without types as

abstract class Book {

  val id 
  val name 
  val book 

}

Says incorrect value declaration. If methods can be declared without explicit type annotations.

abstract class Book {

  val id : Int
  val name : String
  val book : Long

  def aMethodWithNoTypeAnnotation

}

Why can't variables work the same way? Is this a limitation for the JVM?

+4
source share
1 answer

Scala does not have global type inference, only local type inference. Type a valor is vardefined as the type of expression used to initialize it. Abstract valand varnot initialized, so there is nothing to deduce the type from.

, Unit. . Unit val var: Unit, ?

+6

Source: https://habr.com/ru/post/1667174/


All Articles