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
Dataformのリポジトリを立ち上げるときにまずやること / dataform-day0-2026
snhryt
0
170
Language Server 使ってる? 〜VSCode と Zed の場合〜 / Are you using a Language Server? ~For VS Code and Zed~
handlename
0
790
ローカルLLMを使ってB2Bサービスを作っていての学び
yaotti
0
200
TAKTでAI駆動開発の品質を設計する
j5ik2o
7
1.4k
気圧・高度・GPSを記録&可視化するアプリ「Koudo」を作った話
hjmkth
1
290
AI時代のUIはどこへ行く?その2!
yusukebe
22
7.4k
Go1.27で導入されるジェネリクスメソッドでできること
mackee
0
140
そのテスト、説明できますか?~LWテスト戦略FW~のご紹介
nakahara
0
150
C# and C++ Interoperability - cho-dotnetnew
harukasao
0
260
Oxcを導入して開発体験が向上した話
yug1224
4
320
生成AI時代にこそ効くGo | Why Go Works in the Age of Generative AI
mom0tomo
8
3.3k
Vite+ Unified Toolchain for the Web
naokihaba
0
320
Featured
See All Featured
Reflections from 52 weeks, 52 projects
jeffersonlam
356
21k
Design in an AI World
tapps
1
250
HTML-Aware ERB: The Path to Reactive Rendering @ RubyCon 2026, Rimini, Italy
marcoroth
1
200
Collaborative Software Design: How to facilitate domain modelling decisions
baasie
1
250
30 Presentation Tips
portentint
PRO
1
330
So, you think you're a good person
axbom
PRO
2
2.1k
Code Review Best Practice
trishagee
74
20k
Ethics towards AI in product and experience design
skipperchong
2
310
Navigating the moral maze — ethical principles for Al-driven product design
skipperchong
2
390
The Straight Up "How To Draw Better" Workshop
denniskardys
239
140k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
46
2.9k
Avoiding the “Bad Training, Faster” Trap in the Age of AI
tmiket
0
180
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