LoginSignup
1
0

More than 5 years have passed since last update.

【問題解決】 match式で`pattern type is incompatible with expected type;`というエラーが発生

Last updated at Posted at 2018-03-13

環境

  • 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研修資料で勉強している際にハマった問題です。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0