Idiomatic Scala

#1

What is (more) idiomatic in Scala:

  1. val vBox: VBox = FXMLLoader.load(getClass.getResource("VBox.fxml"))
  2. val vBox = FXMLLoader.load[VBox](getClass.getResource("VBox.fxml"))
#2

I don’t think there’s a clear answer. I would probably lean towards (1) personally, just because I find that type attribution often makes debugging a bit easier and code slightly easier to read, but both forms are totally common and reasonable…

#3

The later is useful for quick hacking, experimenting. Maybe it’ll be thrown away with in 2 minutes of being written. Once code has a minimum level of stability then its generally nice and helpfully to ascribe types.

I think it is also a matter of personal /organisation / company taste. Some people value brevity more, some value precision, safety and documentation more. I think its good that Scala allows different styles of coding. I believe one of Scala’s initial goal was to appeal to Dynamic programmers, by offering similar conciseness but with Static safety and type inference.

#4

I always supply type annotations for val and def (and you should too!) so 1 is the way I would write it.

#5

I would go with +1 on 1.

Same reason we like:

List(1,2,3)

more than

List[Int](1,2,3)
#6

There’s always a third option:

val vBox = FXMLLoader.load(getClass.getResource("VBox.fxml")): VBox

:stuck_out_tongue:

As for the original case, it depends. Second option is better if later you want to chain it with something else, e.g:

val vBoxAttribute = FXMLLoader
  .load[VBox](getClass.getResource("VBox.fxml"))
  .vBoxAttribute

But OTOH non-private object members should have explicit types, so if there is something like:

class Something {
  val vBox: VBox = ???
}
object Something {
  val vBox: VBox = ???
}

I wouldn’t hide the explicit type annotations of fields above.

1 Like