Why does Scala apply thunks automatically, sometimes?

前端 未结 4 683
花落未央
花落未央 2021-02-05 03:39

At just after 2:40 in ShadowofCatron\'s Scala Tutorial 3 video, it\'s pointed out that the parentheses following the name of a thunk are optional. \"B

4条回答
  •  礼貌的吻别
    2021-02-05 04:25

    Your guess is correct - Scala has type-dependent semantics regarding the evalution of expressions.

    Like Ruby, it always evaluates thunks even without parentheses. (This might have advantages for interaction purposes since you can switch pure and possibly impure operations without having to change the syntax.)

    But since Scala has a powerful static type system, it can break the above rule and save the programmer from explicitly partially applying the functions in cases where the result of an evalution wouldn't make sense from a type perspective.

    Note that type-dependent evalution can even simulate call-by-name


    Now is type-dependent evalution behaviour is good or bad? ... Well, it can certainly lead to confusing cases like yours and doesn't feel that pure any more. But in most cases, it just works as intended by the programmer (making code more concise) - So let's say, it's okay.

提交回复
热议问题