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
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
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
360
技術的負債解消で開発者の未来を開く- AIの力でコード刷新
kmd2kmd
0
120
Mujeres en SEO Summit 2026 - Greatest Disaster Hits en Web Performance
guaca
0
200
ランチタイムLT会3周年!ランチタイムLT会を3年間続けられたお話
y0hgi
1
110
OSもどきOS
arkw
0
590
Observability in Practice:Grafana 與 Edge Device SRE 的那些事
blueswen
0
180
肥大化するレガシーコードに立ち向かうためのインターフェース分離と依存の逆転 / JJUG CCC 2026 Spring
hirokunimaeta
0
640
Creating Composable Callables in Contemporary C++
rollbear
0
170
The NotImplementedError Problem in Ruby
koic
1
960
IBM Bobを活用したレガシーアプリの最新化
oniak3ibm
PRO
1
220
エンジニア向け会社紹介/Findy Company Profile
findyinc
6
350k
Honoでのサプライチェーン侵害対策 〜 3つのライブラリに学ぶ
yusukebe
7
1.5k
Featured
See All Featured
Neural Spatial Audio Processing for Sound Field Analysis and Control
skoyamalab
0
350
End of SEO as We Know It (SMX Advanced Version)
ipullrank
3
4.2k
Being A Developer After 40
akosma
91
590k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
123
22k
The Curse of the Amulet
leimatthew05
2
13k
How STYLIGHT went responsive
nonsquared
100
6.2k
The AI Search Optimization Roadmap by Aleyda Solis
aleyda
1
5.9k
Chasing Engaging Ingredients in Design
codingconduct
0
230
The Limits of Empathy - UXLibs8
cassininazir
1
370
技術選定の審美眼(2025年版) / Understanding the Spiral of Technologies 2025 edition
twada
PRO
118
120k
svc-hook: hooking system calls on ARM64 by binary rewriting
retrage
2
310
<Decoding/> the Language of Devs - We Love SEO 2024
nikkihalliwell
1
260
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