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
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
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.9k
scala-on-ddd
crossroad0201
31
16k
Other Decks in Programming
See All in Programming
エンジニア向け会社紹介/Findy Company Profile
findyinc
6
360k
これからAgentCoreを触る方へトレンドはGatewayです
har1101
6
500
Generative UI & AI-Assistants for Your Angular Solutions
manfredsteyer
PRO
1
210
Embedded SREと共に達成した会員管理システムのAWS移行 - SRE NEXT 2026 ランチスポンサーセッション
niftycorp
PRO
1
2.9k
SLOをサービス品質の共通言語にするために 取り組んできたこと
wakana0222
0
540
型も通る、synthも通る、それでも危ない 〜AIのCDKの権限とコストを機械で検証する〜 / It Passes Type Checks, It Passes Synth Checks, but It’s Still Risky — Automatically Verifying Permissions and Costs in AI’s CDK —
seike460
PRO
1
410
Haskell/Servantを通してWebミドルウェアを捉え直す
pizzacat83
1
610
1年で人数1.5倍、PR数5.5倍増。 品質とアウトカムはどうなったか、 何が効いたか
ike002jp
0
140
変わらないものが、変わるものを決める — 意図駆動開発 × イベントソーシング × イミュータブル | What Doesn't Change Decides What Can — IDD × Event Sourcing × Immutability
tomohisa
0
110
共通化で考えるべきは、実装より公開する型だった
codeegg
0
270
使用 Meilisearch 建立新聞搜尋工具
johnroyer
0
160
AIを活用したE2Eテスト実装効率化のあゆみ / ebisu-mobile-14-kotetu
kotetuco
0
180
Featured
See All Featured
jQuery: Nuts, Bolts and Bling
dougneiner
66
8.5k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
2.8k
Color Theory Basics | Prateek | Gurzu
gurzu
0
390
Abbi's Birthday
coloredviolet
3
8.8k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
11
970
Raft: Consensus for Rubyists
vanstee
141
7.6k
Building Flexible Design Systems
yeseniaperezcruz
330
40k
What the history of the web can teach us about the future of AI
inesmontani
PRO
1
640
Fashionably flexible responsive web design (full day workshop)
malarkey
408
67k
Test your architecture with Archunit
thirion
1
2.3k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
32
3.9k
How To Stay Up To Date on Web Technology
chriscoyier
790
250k
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