More Related Content Similar to Scala 初心者向けlt (20) Scala 初心者向けlt2. 自己紹介
for {
Type <- Person
Name <- Keigo Magma
Github <- k5jp1015
Job <- Server Side Engineer
Scala Experience <- 4 Month
Hobby <- Training(筋トレのことです♪)
} yeild Self Introduction(自己紹介)
2
6. ふつうな感じ
// 認証取得用メソッド定義
def getAuth(…) = {……}
// 外部ストレージからファイルをダウンロードするメソッド定義
def getFile(...., authObj: Authentication):File = {……}
// 外部ストレージのファイルを削除するメソッド定義
def deleteFile(...., authObj: Authentication):boolean = {……}
// 認証用オブジェクト取得
val authObj = this.getAuth(…)
// ファイルの取得
val file = this.getFile(...., authObj)
// ファイルの削除
val file = this.deleteFile(...., authObj)
6
7. implicit parameter使って
イイ感じ(-ω☆)キラリ
// 認証取得用メソッド定義
def getAuth(…) = {……}
// 外部ストレージからファイルをダウンロードするメソッド定義
def getFile(...., implicit authObj: Authentication):File = {……}
// 外部ストレージのファイルを削除するメソッド定義
def deleteFile(...., implicit authObj: Authentication):boolean = {……}
// 認証用オブジェクト取得
implicit val authObj = this.getAuth(…)
// ファイルの取得
val file = this.getFile(....)
// ファイルの削除
val file = this.deleteFile(....)
7
14. scala> val x = "正"
x: String = 正
scala> check(x)
res2: Boolean = true
scala> val x = 1
x: Int = 1
scala> check(x)
res1: Boolean = true
scala> val x = Seq("1","false","etc")
x: Seq[String] = List(1, false, etc)
scala> check(x)
res0: Boolean = true
String
Int
Seq(String)
14
17. Step 2
object Checker{
implicit val stringChecker:Checker[String] = new
Checker[String] {
override def check(x: String) = {
x match {
case "true" | "1" | "正"=> true
case _ => false
}
}
}
implicit val intChecker:Checker[Int] = new Checker[Int] {
override def check(x: Int) = {
x match {
case 1 => true
case _ => false
}
}
}
implicit val seqStringChecker:Checker[Seq[String]] = new
Checker[Seq[String]] {
override def check(x: Seq[String]) = x.contains("true") ||
x.contains("1") || x.contains("正")
}
}
step1で用いた型に対して、
「String」「Int」「Seq[String]」の引数を
取るときの具体的な定義をしてあげる!!
17
18. Step 3
object activeChecker{
def check[A](x:A)(implicit C:Checker[A])
=C.check(x)
}
「A」という型をもつ引数とimplicit
parameterオブジェクトが必要だよ!
Cがもっているメソッドを引数xを使って実
行するよ!!
18