読み解き PiS3: def の後のイコールのありなし

  • def の後の body の前に = を置かない場合と置く場合の違いが気になっていた。
    • = を置かない場合はメソッド/関数の戻り値は Unit になる。
    • = を置く場合はメソッド/関数の戻り値を任意に指定する。

The equals sign that precedes the body of a function hints that in the functional world view, a function defines an expression that results in a value.The basic structure of a function is illustrated in Figure 2.1. (Chapter 2. First Steps in Scala)

  • 自分で sbt console から試してみる。
scala> def hello(s: String) { println(s"hello, $s.") }

hello: (s: String)Unit

scala> hello("world")
hello, world.
scala> def hello(s: String) = { println(s"hello, $s.") }
hello: (s: String)Unit

scala> hello("world")
hello, world.
scala> def hello(s: String): Unit = { println(s"hello, $s.") }

hello: (s: String)Unit

scala> hello("world")
hello, world.
scala> def hello(s: String): String = { println(s"hello, $s.") }
<console>:11: error: type mismatch;
found : Unit
required: String
def hello(s: String): String = { println(s"hello, $s.") }
^
scala> def hello(s: String): String = { "hello, " + s + "." }
hello: (s: String)String

scala> hello("world")
res5: String = hello, world.
  • 同じ疑問を持っている方が説明してくれていて助かった。( ・∀・)

blog.jessitron.com