Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Scalaで自然文っぽくコードを書く
Search
Yohei TSUJI
May 23, 2019
Programming
1.1k
2
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Scalaで自然文っぽくコードを書く
Yohei TSUJI
May 23, 2019
More Decks by Yohei TSUJI
See All by Yohei TSUJI
Akka Persistence Typedにおけるドメインオブジェクトの実装パターン / Pattern of Implement Domain Object with Akka Persistence Typed
crossroad0201
1
570
Lightbend Academyでリアクティブシステムの基礎を学ぼう - JJUG LT
crossroad0201
0
460
Lightbend Academyオンライントレーニングを受けてみた
crossroad0201
4
1.5k
ドメイン駆動設計でモブワークしました
crossroad0201
5
1.1k
エンタープライズ Scala
crossroad0201
4
2.4k
practice-DDD-with-Scala_en
crossroad0201
3
2.8k
scala-on-ddd
crossroad0201
31
16k
Other Decks in Programming
See All in Programming
TypeScript+Orvalで実現する型安全かつ堅牢でスケーラブルなマルチチャネル通知基盤 / TSKaigi Night talks ~after conference~
d0riven
0
290
さぁV100、メモリをお食べ・・・
nilpe
0
130
Why Laravel apps break—Mastering the fundamentals to keep them maintainable
kentaroutakeda
1
340
CSC307 Lecture 17
javiergs
PRO
0
310
密結合なバックエンドから TypeScript のコードを生成する
kemuridama
1
740
Claspは野良GASの夢をみるか
takter00
0
170
dRuby over BLE
makicamel
2
320
プラグインで拡張される Context をtype-safe にする難しさと設計判断
kazupon
2
590
キャリア迷子上等 ─ "ない道"は自分で作ればいい
16bitidol
3
970
開発体験を左右するライブラリの API 設計 - GraphQL スキーマ構築ライブラリから考える #tskaigi
izumin5210
2
1.6k
Old Dog, New Tricks: The Java 25 Reinvention - JNation
bazlur_rahman
0
140
AI時代のUIはどこへ行く?その2!
yusukebe
19
6.6k
Featured
See All Featured
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
31
3.2k
Thoughts on Productivity
jonyablonski
76
5.2k
The Hidden Cost of Media on the Web [PixelPalooza 2025]
tammyeverts
2
320
Rebuilding a faster, lazier Slack
samanthasiow
85
9.5k
How Software Deployment tools have changed in the past 20 years
geshan
0
34k
End of SEO as We Know It (SMX Advanced Version)
ipullrank
3
4.2k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
34
2.8k
Six Lessons from altMBA
skipperchong
29
4.3k
Mozcon NYC 2025: Stop Losing SEO Traffic
samtorres
1
250
The Illustrated Children's Guide to Kubernetes
chrisshort
51
52k
Google's AI Overviews - The New Search
badams
0
1k
DBのスキルで生き残る技術 - AI時代におけるテーブル設計の勘所
soudai
PRO
65
55k
Transcript
Scalaで⾃然⽂っぽく コードを書く 2019/05/23 Scala関⻄ × MixLeap
⾃⼰紹介 Yohei TSUJI(@crossroad0201) Scalaはエンジニア⼼をくすぐる⾔語です 2
Scalaは DSL(※) を作成するための ⾔語仕様が豊富です ので… 3 ※DSL=Domain Specific Language
あたかも⾃然⽂の⽂章のように コードを書けます 4
百聞は⼀⾒にしかず 5
例その1 Scala Testのアサート⽂ 6
7 "abc" should have length 3 false should not be
true 引⽤:http://www.scalatest.org/user_guide/using_matchers
8 new File("test.txt") should be a 'file class Example {
def isOrganization: Boolean = true } new Example() should be an 'organization 引⽤:http://www.scalatest.org/user_guide/using_matchers
9 Seq("apple", "orange") should contain ("apple") (Seq("A", "B", "C") should
contain only ("a", "b", "c")) (after being lowerCased) 引⽤:http://www.scalatest.org/user_guide/using_matchers
10 case class Book(title: String, author: String) val book =
Book( "Programming in Scala", "Martin Odersky” ) book should have( 'title ("Programming in Scala"), 'author ("Martin Odersky") ) 引⽤:http://www.scalatest.org/user_guide/using_matchers
例その2 RESTful APIのルーティング 11
12 object WebServer extends HttpApp { override def routes: Route
= path("hello") { get { complete(HttpEntity( ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>” )) } } } class MinimalHttpApp extends HttpApp { @Override protected Route routes() { return path("hello", () -> get(() -> complete("<h1>Say hello to akka-http</h1>") ) ); } } Scala Java 引⽤: https://doc.akka.io/docs/akka-http/current/routing-dsl/index.html
例その3 ⽇本語でも 13
14 val 辻 = ユーザー("辻") val Scala関⻄MixLeap = イベント( タイトル
= "Scala関⻄×MixLeap", 募集⼈数 = 60 ) 辻 は (Scala関⻄MixLeap に申し込む) match { case 参加できます(_受付票) => println(s"受付票は ${_受付票} です") case 補⽋です(_キャンセル待ち) if _キャンセル待ち.そんなに待てない => _キャンセル待ち をキャンセルする() println("キャンセル待ちが多いので、申込みをキャンセルしました") case 補⽋です(_キャンセル待ち) => println(s"${_キャンセル待ち.待ち⼈数}⼈待ちです") }
DSL作成で知っておきたい Scalaの構⽂ 15
関数名に記号が使える Scalaでは関数の名前に記号が使えます。 16 class Path(path: String) { def /(child: String):
Path = ??? } new Path("foo")./("bar")./("hoge")./("moge") new Path("foo") / "bar" / "hoge" / "moge"
レシーバーとメソッドの区切りに 半⾓スペースが使える メソッドを呼び出す場合は、レシーバーとメソッド名の区切りに ピリオドだけでなく半⾓スペースも使えます。 17 class User(name: String) { def
renameTo(newName: String) = ??? def bornIn(year:Int, month: Int, day:Int) = ??? } val user = new User("tsuji") user.renameTo("TSUJI") user renameTo "TSUJI" user.bornIn(2019, 5, 20) user bornIn (2019, 5, 20)
パラメタ指定時の (…) を省略できる パラメタの数が1つだけメソッドは、パラメタ指定時の (…) を省 略できます。 18 class Greeter(name:
String) { def say(greeting: String) = ??? } new Greeter("Tsuji").say("Hello") new Greeter("Tsuji") say "Hello"
パラメタを名前指定できる 関数を呼び出す場合などに、 パラメタを パラメタ名=パラメタ値 形式で指定できます。 19 def address( postCode: Option[String]
= None, country: String, state: Option[String] = None, prefecture: String, city: String, address: String, building: Option[String] = None ) = ??? address( postCode = Some("999-9999"), country = "Japan", prefecture = "Osaka", city = "Osaka", address = "1-1-1" )
{…} でパラメタを渡せる Scalaでは関数にパラメタを渡すときに (…) だけでなく {…} も 使えます。 {…} を使うことであたかも⾔語仕様で⽤意されている構⽂のよ
うに関数を使うことができます。 20 trait Transaction def transactional[RESULT](f: Transaction => RESULT): RESULT = ??? transactional(tx => /*処理*/) transactional { tx => // 処理 }
既存の型にメソッド追加できる 「Implicit conversion」と呼ばれる機能で、既存の型を修正する ことなくメソッドを追加(したかのように⾒せる)できます。 ※ただし乱⽤しないように!! 21 implicit class GreetableString(value: String)
{ def sayHello: String = s"Hello $value” } "World" sayHello
まとめ • Scalaは⾔語仕様レベルでDSLが考慮されており、 ⾃然な表現のDSLを作成することができます。 • 業務アプリケーションでも、うまくDSLを作ることが 可読性の⾼いコードを記述する助けになるはずです。 • ドメイン駆動設計を採⽤している場合は、ドメイン モデルをDSLにすることで、ユースケースを⾃然⽂
のように書けます。 22
ご清聴ありがとうございました 23