Created
August 26, 2022 00:59
-
-
Save ugdark/e3754a012270632eca158e173795c179 to your computer and use it in GitHub Desktop.
scala sealed確認
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.domain | |
import com.example.domain | |
import org.scalatest.funspec.AnyFunSpec | |
import scala.reflect.runtime.universe | |
sealed trait IError { | |
val template: String | |
} | |
sealed trait NotSealed | |
sealed trait AccountError extends NotSealed | |
object AccountError { | |
case object Id extends AccountError with IError { | |
override val template: String = "アカウントIdは半角英数字の4文字以上100文字以下です。" | |
} | |
case object Name extends AccountError with IError { | |
override val template: String = "アカウント名は4文字以上20文字以下です。" | |
} | |
} | |
sealed trait BuildingError | |
object BuildingError { | |
case class Name() extends BuildingError with IError { | |
override val template: String = "名前は半角英数字の1文字以上100文字以下です。" | |
} | |
case class Address() extends BuildingError with IError { | |
override val template: String = "住所はは4文字以上255文字以下です。" | |
} | |
} | |
// sealed つけないと matchのテンプレート時に case _ => ??? が追加される | |
trait RoomError | |
object RoomError { | |
case object Count extends RoomError | |
} | |
class InvalidErrorTest extends AnyFunSpec { | |
it("IDEでのパターンMatch展開の確認") { | |
val a: AccountError = AccountError.Name | |
a match { | |
case AccountError.Id => ??? | |
case AccountError.Name => ??? | |
} | |
val b: BuildingError = BuildingError.Name() | |
b match { | |
case BuildingError.Name() => ??? | |
case BuildingError.Address() => ??? | |
} | |
val i: IError = AccountError.Name | |
i match { | |
case AccountError.Id => ??? | |
case AccountError.Name => ??? | |
case BuildingError.Name() => ??? | |
case BuildingError.Address() => ??? | |
} | |
val n: NotSealed = AccountError.Id | |
// sealed trait AccountError にNotSealedをつけても | |
// 下記みたいに展開されない | |
n match { | |
case _: AccountError => ??? | |
} | |
val r: RoomError = RoomError.Count | |
// これはただのsealedの効果確認用 | |
r match { | |
case RoomError.Count => ??? | |
case _ => ??? | |
} | |
// InvalidErrorのすべてのtemplateを取得する方法 | |
succeed | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment