■ はじめに
Scala が慣れない、、、 今回は、Scala の メソッド について扱う。 なお、Scala の 場合、メソッド と 関数 は異なる。
Scala ~ 基本編 / 関数 ~
https://dk521123.hatenablog.com/entry/2023/10/09/232838
目次
【1】構文 【2】戻り値 【3】使用上の注意 【4】implicit 1)Implicit conversion 2)Implicit parameter(文脈引き渡し) 【5】可変長引数
【1】構文
def メソッド名(引数名1: データ型, ...): 戻り値のデータ型 = 式 or ブロック // 個人的に、「=」の部分を書くの忘れてしまう、、、
式の場合
def sampleMethod1(name: String): String = s"Hello, ${name}!!"
ブロックの例
def sampleMethod2(name: String): String = { // e.g. name = "Mike", return value is "Hello, Mike!!" s"Hello, ${name}!!" }
【2】戻り値
* Java の void は、「Unit」 * return は基本書かないらしい(途中で関数抜けるとき位?)
【3】使用上の注意
* 引数がない場合、「()」を省略して関数を呼び出すことも可能 => 正規表現のメソッドは、引数なしで定義されているので、()に違和感があった、、、
【4】implicit
cf. implicit = 暗黙の <-> explicit 明確な、明白な * 以下のサイトが分かりやすい
http://techtipshoge.blogspot.com/2019/06/scala-implicit.html
https://zenn.dev/at12/articles/7ac49ccbe4865b
https://scala-text.github.io/scala_text/implicit.html
1)Implicit conversion
* 暗黙の型変換をユーザが定義できる機能 => 便利だが、使いすぎるとコードが追いづらくなる、、、
サンプル
object Main extends App { class Hello(val name: String) { def printHello(): Unit = { println(s"Hello, ${this.name}!!!") } } class World(val name: String) { def printWorld(): Unit = { println(s"World, ${this.name}...") } } implicit def toWorld(hello: Hello): World = { new World(hello.name) } val hello = new Hello("Mike") hello.printHello // Hello, Mike!!! hello.printWorld // World, Mike... <= 勝手にtoWorldを呼び出してくれる }
2)Implicit parameter(文脈引き渡し)
object Main extends App { def sayHi(greeting: String)(implicit name: String): Unit = { println(s"${greeting}, ${name}!!!") } // 暗黙のパラメータを事前に設定 implicit val name = "Mike" sayHi("Hello") // Hello, Mike!!! }
【5】可変長引数
def output(values: String*) { values.foreach(print) } def output(values: String_*) { values.foreach(print) }
関連記事
Scala ~ 環境構築編 ~
https://dk521123.hatenablog.com/entry/2023/03/10/193805
Scala ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2023/03/12/184331
Scala ~ 基本編 / クラス ~
https://dk521123.hatenablog.com/entry/2023/03/14/000857
Scala ~ 基本編 / コレクション ~
https://dk521123.hatenablog.com/entry/2023/03/13/000345
Scala ~ 基本編 / 関数 ~
https://dk521123.hatenablog.com/entry/2023/10/09/232838
Scala ~ YAML ~
https://dk521123.hatenablog.com/entry/2023/03/16/012034