環境
- Scala 2.12.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_152)
問題
以下のscalaコードをビルドすると、pattern type is incompatible with expected type
というエラーが発生しました。
sample.scala
val s = Some("hoge")
val result = s match {
case Some(str) => str
case None => "not matched"
}
error
Error:(46, 10) pattern type is incompatible with expected type;
found : None.type
required: Some[String]
case None => "not matched"
原因
変数s
の型がOptionでなくSomeであることが原因でした。
エラーの内容は「Some[String]
型を期待するけど、None
が見つかったよ」という意味です。
val s:Option[String] = Some("hoge")
に変更して、解決しました。
「OptionはSomeとNoneを持つ」という事実を知っていればすぐ解決できるはずなんですが…
これに30分間も使ってしまったので、Qiitaに投稿しました。
補足
ドワンゴのscala研修資料で勉強している際にハマった問題です。