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
FDEが実現するAI駆動経営の現在地
gonta
2
190
【やさしく解説 設計編・中級 #1】一つの車に、運転手は一人 ~ある倉庫システムの事例から~
panda728
PRO
0
190
フィードバックで育てるAI開発
kotaminato
1
120
AI時代のPHPer生存戦略 ~「言語、もうなんでもよくない?」に本気で向き合う~
vivion
0
130
言語を使う側から、作る側へ。 自作 Lisp で得た新たな気づき。
andpad
0
130
act1-costs.pdf
sumedhbala
0
240
分散システム、なんですぐ死んでしまうん?耐障害性を高めたいあなたのためのレジリエンスパターン入門
mshibuya
7
6.7k
Laravelで学ぶ Webアプリケーションチューニング入門/web_application_tuning_101
hanhan1978
4
1.2k
【やさしく解説 設計編・中級 #6】良いアーキテクチャとは ~ 一本の登り道の、行き先 ~
panda728
PRO
0
170
トークンをケチるな、設計しろ:GitHub Copilotを賢く使うコンテキスト戦略
ochtum
0
330
どこまでゆるくて許されるのか
tk3fftk
0
520
Featured
See All Featured
Bootstrapping a Software Product
garrettdimon
PRO
307
120k
Put a Button on it: Removing Barriers to Going Fast.
kastner
60
4.4k
[RailsConf 2023] Rails as a piece of cake
palkan
59
6.8k
Unlocking the hidden potential of vector embeddings in international SEO
frankvandijk
0
880
Agile Actions for Facilitating Distributed Teams - ADO2019
mkilby
0
220
We Analyzed 250 Million AI Search Results: Here's What I Found
joshbly
1
1.6k
How to make the Groovebox
asonas
2
2.3k
Color Theory Basics | Prateek | Gurzu
gurzu
0
390
Faster Mobile Websites
deanohume
310
32k
Information Architects: The Missing Link in Design Systems
soysaucechin
0
1k
Tell your own story through comics
letsgokoyo
1
1k
Mozcon NYC 2025: Stop Losing SEO Traffic
samtorres
1
410
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