SlideShare a Scribd company logo
python to scala
簡介
● inwinSTACK
● Openstack contributor
○ Openstack Kolla core member
● kjellytw at gmail dot com
● http://www.blackwhite.
tw/
Java to Scala
● Java to Scala
Python
● Object-oriented,
● Imperative
● Dynamic type
● Interpreted languages
● Support shell
Scala
● Functional programming
● Static type
● Object-oriented
● Type inference
● Lazy (non-strict) evaluation
● Compiled languages
● Support shell
python vs scala
● statement,
expression.
● a + b => a.__add__
(b)
● f(a,b) => f.__call__
(a,b)
● everything
"evaluates" to a
value.
● a + b => a.+(2)
● f(a,b) => f.apply(a,
b)
variable - python vs scala
a = 1 ● The return value of
expression is `()`.
var a = 1
var a: Int = 1
const - python vs scala
● python doesn’t
support const.
● The return value of
expression is `()`.
val a = 1
val a: Int = 1
lazy
● Not support in native python. (Maybe some
library support it.
● Initialization is deferred until it is accessed
for the first time
● Check whether the value has already been
initialized before a lazy value is accessed.
lazy
● lazy var words = scala.io.Source.fromFile
("/usr/share/dict/words").mkString
● lazy val fibs: Stream[BigInt] = BigInt(0) #::
BigInt(1) #:: fibs.zip(fibs.tail).map { n => n.
_1 + n._2 }
if-else
● statement
if a > 5:
print(a)
else:
print()
● expression
val x = if(a>5) {1} else 2
val y = if(1!=1) 1 //y == ()
while
while a > 5:
print(a)
a -= 1
● The return value of
expression is `()`.
while ( a > 5) {
print(a)
a -= 1
}
def loop(x: Int, xs: List[Int]): Int = {
var max_value = x
var rest = xs
while (rest != Nil) {
if (max_value < rest.head) max_value = rest.
head
rest = rest.tail
}
max_value
tail recursion
def loop(lst: List[Int], maxValue: Int): Int =
lst match {
case Nil => maxValue
case x :: xs => if (x > maxValue) loop(xs,
x) else loop(xs, maxValue)
}
tail recursion
def max(lst: List[Int]): Int = {
lst match {
case Nil => 0
case x :: xs => loop(xs, x)
}
}
tail recursion
● a tail call might lead to the same
subroutine being called again later in the
call chain.
● a tail recursive function is transformed into
a loop by the compiler.
● use `@tailrec`
do while
● Not support do {
println(a)
a -= 1
while( a > 5)
for
list comprehension vs for yield
python
scala: the syntax is similar with for.
generator vs stream
They are not the same. But they are similar in
some case.
function
● You can define
many function with
the same name. But
only the function
which is executed in
last time will be
called.
● Support overloading
scala function
def func(a: Int, b: Int) :Unit = {
1
}
scala function
1. def fun = 1 // for pure function
2. def fun() {println(“S”)} # for side effect
function argument
● support variable-
length argument,
keyworded
argumen, default
argument.
● support variable-
length argument,
default argument,
call-by-name
argument.
variable-length , keyworded , default
argument
def func(a, b=1, *args, **kwargs):
pass
def func(a: Int, b: Int = 1, args: Int*) = {
1
}
call-by-name argument
● python doesn’t support call-by-name.
● def mywhile(condition: => Boolean, body: => Unit)
def mywhile(condition: => Boolean, body: => Unit): Int = {
def loop(count: Int): Int = {
if (condition) {
body; loop(count + 1)
} else count
}
loop(0)
}
var a = 1
print(mywhile({ a < 5 }, { a += 1 }))
function return
● use `return` if you
want to return
something.
● if there are no
return in function
body, it will return
`None`.
● avoid to use
`return` keyword.
● if there are no
return in function
body, it will return
the value of the
last expression
match-case
● python doesn’t support match-case.
match-case
x.asInstanceOf[Any] match {
case x :: xs => println(x)
case (a, b, c) => println(a)
case p @ Some(v) if v == 2 => println(p)
case x: Int if x != 2 => println(x)
case _ => println(“None”)
}
class
1. multi inheritance
2. public
3. Not support
overloading
1. single inheritance
2. public, protect,
private
3. Support overloading
class constructor
class My(object):
def __init__(self, x):
self.x = x
self.odd = x%2 ==0
def print_x(self):
print(self.x)
class My(var x: Int) {
var odd = x % 2 ==0
def print_x() {
println(x)
}
}
scala auxiliary constructor
class Length(val length: Int) {
def this(str: String) { this(str.length) }
def this(list: List[Any]) { this(list.length) }
}
new Length(5)
new Length(“Hi”)
new Length(List(1,2))
duck typing
class Length1(val length: Int) {
def this(o: {def length:Int}) {
this(o.length)
}
}
● All thing is
duck typing
in python.
● scala support duck typing.
scala companion object
● singleton object
● companion object
Singleton object
object Main {
def sayHi() {
println("Hi!");
}
}
companion object
class Main {
def sayHelloWorld() {
println("Hello
World");
}
}
object Main {
def sayHi() {
println("Hi!");
}
method,used for
instance
static method,
used for class
How to create instance?
class A(object):pass
a = A()
class A {}
val a = new A
class B{}
object B{def apply() = new B}
val bB = B()
Python
Scala
Type checking and cast
1. isinstance(a, str)
2. issubclass(A,
object)
3. a.__class__
1. "S".isInstanceOf[String]
2.
3.
4. "S".asInstanceOf
[String]
Type checking and cast
if isinstance(a, int):
print(“int”)
elif isinstance(a, str):
print(“str”)
a mtach {
case _: Int =>
println(“int”)
case _: String =>
println(“Str”)
}
class inheritance
● Method Resolution
Order
● class X(A, B):pass
● X.__mro__
● single inheritance
● need `override` when
overriding
● class X extends Any
scala trait
● trait is like java interface but allows
concrete implementations.
● class A extends B with C with D
○ extends + class|trait
○ with + trait
case class
● python doesn’t support case class.
● case class generate the following method:
○ equals
○ apply for companion object .
○ unapply for companion object.
Why we need case class?
def Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
person = Person(“bill”, 5)
Why we need case class?
case class Person(var name:String, var age:Int)
val person = Person(“Bill”, 5)
More case calss
person match {
case Person(name, age) if name == "X" =>
s"$name,$age"
case _ => "Nothing"
}
Scala hierarchy
Python hierarchy
I don’t care.
package
● folder with
`__init__.py` file
● package com.abc.
name
import
● the way to use the
code in other file.
● use short name
import
● the way to use the
code in other file.
● use short name
Implicit
● python doesn’t support implicit.
● Implicit Conversions
○ implicit defwrapString(s: String): WrappedString
● Implicit Parameters
○ implicit val n: Int = 5
○ def add(x: Int)(implicit y: Int) = x + y
● more thing ...
Scala type parameters
● List[String](); def drop1[A](l: List[A]) = l.tail
Scala type parameters
● List[String](); def drop1[A](l: List[A]) = l.tail
● more thing about:
○ Bounds -> def biophony[T <: Animal]
○ Quantification -> def count(l: List[_]) = l.size
○ Variance
Int
● int, long
● nerver overflow
● Int(32-bit signed) or
Long(64-bit signed)
or BigInt
● BitInt supports +,%,*
● care for overflow
Boolean
● True and False
● False or True
● not True
● true && false
● true || false
● !true
● short-circuit
String
● no char
● one line string:
○ “string”
○ ‘string’
● multiline string:
○ “””dddd”””
○ ‘’’ccc’’’
○ “abcd”[1]
● char => ‘c’
● string => “c”
● “abcd”(1)
String format
● "%s %d" % ("Hi", 5)
● '{0}'.format('a')
● 'Coordinates:
{latitude}'.format
(latitude='37.24N',)
● i"{names}" #P0510
● "%s".format
(firstName)
● s"Hello, $name"
List in python vs ArrayBuffer in scala
1. List(1, 2, 3, 4)
2. [1, 2, 3, 4]
3. a[3]
4. a[-1]
5. a[1:-1]
6. a[1:-1:-1]
7. a[1] = 1
1. ArrayBuffer(1,2,3,4)
2. new ArrayBuffer[Int]()
3. a(3)
4.
5. a.slice(1, a.length-1)
6.
7. a(1) = 1
List in python vs ArrayBuffer in scala
1. map(a, lambda x:
x+1)
2. b = [i + 1 for i in a if
i % 2 ==0]
1. a.map(_ + 1)
2. val b = for(i <- a if i
% 2 ==0) yield i + 1
a.map(x:Int => {x + 1})
a.map(x => {x+1})
a.map(x => x+ 1)
a.map(_ + 1)
List in python vs ArrayBuffer in scala
1. a.__getitem__
2. a.__setitem__
1. a.apply
2. a.update
ArrayBuffer
new ArrayBuffer(5) vs ArrayBuffer(5)
Scala List
● Linked list
● Optimal for last-in-first-out (LIFO), stack-
like access patterns
● Immutable
● `Nil` means empty list.
Scala List
● List(1, 2, 3)
● 1 :: 2 :: 3 :: Nil
● Nil.::(3).::(2).::(1)
Scala List
def max(lst: List[Int]): Int = {
lst match {
case Nil => 0
case x :: xs => loop(xs, x)
}
}
Scala Async
Future.apply[T](body: ⇒ T)(implicit executor:
ExecutionContext): Future[T]
def combined: Future[Int] = async {
val future1 = slowCalcFuture
val future2 = slowCalcFuture
await(future1) + await(future2)
}
val future1 = slowCalcFuture
val future2 = slowCalcFuture
def combined: Future[Int] = for {
r1 <- future1
r2 <- future2
} yield r1 + r2
django vs play framework2
● python web
framework
● MVT
● support ORM
● scala/java web
framework
● MVC
● support type
checking in views.
django class-based views vs play
controller
def index = Logging {
Action {
Ok("Hello World")
}
}
class MyView(TemplateView):
template_name = "about.html"
Play
Django
django template vs play view
play view
● type checking
● view as function.
○ views.html.list(List
(“1”))
function
argument
function
body
call main
function
list.scala.html
django forms vs play forms
Thank you
The slide will update continuously.

More Related Content

What's hot (20)

PDF
Building a Tagless Final DSL for WebGL
Luka Jacobowitz
 
PDF
Runtime Bytecode Transformation for Smalltalk
ESUG
 
PDF
Kotlin Receiver Types 介紹
Kros Huang
 
PDF
PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...
Pôle Systematic Paris-Region
 
PDF
Kotlin Overview
Silicon Straits
 
PPTX
C++ Generators and Property-based Testing
Sumant Tambe
 
PDF
What make Swift Awesome
Sokna Ly
 
PDF
How to Think in RxJava Before Reacting
IndicThreads
 
PDF
Rxjava 介紹與 Android 中的 RxJava
Kros Huang
 
PDF
Joblib for cloud computing
Alexandre Abadie
 
PPTX
Iron Languages - NYC CodeCamp 2/19/2011
Jimmy Schementi
 
PPTX
Introduction to Kotlin Language and its application to Android platform
EastBanc Tachnologies
 
PPTX
Kotlin presentation
MobileAcademy
 
PDF
Reactive Programming in the Browser feat. Scala.js and PureScript
Luka Jacobowitz
 
PDF
A quick and fast intro to Kotlin
XPeppers
 
PDF
Halogen: Past, Present, and Future
John De Goes
 
PPTX
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
PDF
MTL Versus Free
John De Goes
 
PDF
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Romain Dorgueil
 
PPTX
Lua Study Share
Vincent Chang
 
Building a Tagless Final DSL for WebGL
Luka Jacobowitz
 
Runtime Bytecode Transformation for Smalltalk
ESUG
 
Kotlin Receiver Types 介紹
Kros Huang
 
PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...
Pôle Systematic Paris-Region
 
Kotlin Overview
Silicon Straits
 
C++ Generators and Property-based Testing
Sumant Tambe
 
What make Swift Awesome
Sokna Ly
 
How to Think in RxJava Before Reacting
IndicThreads
 
Rxjava 介紹與 Android 中的 RxJava
Kros Huang
 
Joblib for cloud computing
Alexandre Abadie
 
Iron Languages - NYC CodeCamp 2/19/2011
Jimmy Schementi
 
Introduction to Kotlin Language and its application to Android platform
EastBanc Tachnologies
 
Kotlin presentation
MobileAcademy
 
Reactive Programming in the Browser feat. Scala.js and PureScript
Luka Jacobowitz
 
A quick and fast intro to Kotlin
XPeppers
 
Halogen: Past, Present, and Future
John De Goes
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
MTL Versus Free
John De Goes
 
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Romain Dorgueil
 
Lua Study Share
Vincent Chang
 

Viewers also liked (20)

PPTX
How to integrate python into a scala stack
Fliptop
 
PPTX
Immutable infrastructure 介紹與實做:以 kolla 為例
kao kuo-tung
 
PDF
Python y Flink
Paradigma Digital
 
PPTX
Zaharia spark-scala-days-2012
Skills Matter Talks
 
PPTX
Introduction to scala for a c programmer
Girish Kumar A L
 
PDF
Jump Start into Apache Spark (Seattle Spark Meetup)
Denny Lee
 
PPTX
Apache hive
pradipbajpai68
 
PDF
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Databricks
 
PPT
Communication between Java and Python
Andreas Schreiber
 
PDF
Openstack swift, how does it work?
kao kuo-tung
 
PDF
Piazza 2 lecture
elena.pasquinelli
 
PDF
Scala - A Scalable Language
Mario Gleichmann
 
PDF
Neural networks with python
Simone Piunno
 
PDF
Intorduce to Ceph
kao kuo-tung
 
PDF
Indexed Hive
NikhilDeshpande
 
PDF
Fun[ctional] spark with scala
David Vallejo Navarro
 
PDF
Scala: Pattern matching, Concepts and Implementations
MICHRAFY MUSTAFA
 
PPTX
Scala eXchange: Building robust data pipelines in Scala
Alexander Dean
 
PPT
Hive User Meeting August 2009 Facebook
ragho
 
PDF
DataEngConf SF16 - Spark SQL Workshop
Hakka Labs
 
How to integrate python into a scala stack
Fliptop
 
Immutable infrastructure 介紹與實做:以 kolla 為例
kao kuo-tung
 
Python y Flink
Paradigma Digital
 
Zaharia spark-scala-days-2012
Skills Matter Talks
 
Introduction to scala for a c programmer
Girish Kumar A L
 
Jump Start into Apache Spark (Seattle Spark Meetup)
Denny Lee
 
Apache hive
pradipbajpai68
 
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Databricks
 
Communication between Java and Python
Andreas Schreiber
 
Openstack swift, how does it work?
kao kuo-tung
 
Piazza 2 lecture
elena.pasquinelli
 
Scala - A Scalable Language
Mario Gleichmann
 
Neural networks with python
Simone Piunno
 
Intorduce to Ceph
kao kuo-tung
 
Indexed Hive
NikhilDeshpande
 
Fun[ctional] spark with scala
David Vallejo Navarro
 
Scala: Pattern matching, Concepts and Implementations
MICHRAFY MUSTAFA
 
Scala eXchange: Building robust data pipelines in Scala
Alexander Dean
 
Hive User Meeting August 2009 Facebook
ragho
 
DataEngConf SF16 - Spark SQL Workshop
Hakka Labs
 
Ad

Similar to Python to scala (20)

PDF
Functional programming ii
Prashant Kalkar
 
PDF
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
PPTX
Scala
suraj_atreya
 
PDF
The Scala Programming Language
league
 
ODP
Knolx Session : Built-In Control Structures in Scala
Ayush Mishra
 
PPT
Scala Talk at FOSDEM 2009
Martin Odersky
 
ODP
Dynamic Python
Chui-Wen Chiu
 
ODP
Scala ntnu
Alf Kristian Støyle
 
PPTX
Principles of functional progrmming in scala
ehsoon
 
PDF
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
PDF
Railroading into Scala
Nehal Shah
 
PPTX
Scala for curious
Tim (dev-tim) Zadorozhniy
 
PPT
Scala introduction
Yardena Meymann
 
PDF
Lecture 5: Functional Programming
Eelco Visser
 
PDF
Python idiomatico
PyCon Italia
 
PDF
Pydiomatic
rik0
 
PDF
Programming Android Application in Scala.
Brian Hsu
 
PDF
Introductiontoprogramminginscala
Amuhinda Hungai
 
PDF
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
PDF
Introduction to Scala
Aleksandar Prokopec
 
Functional programming ii
Prashant Kalkar
 
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
The Scala Programming Language
league
 
Knolx Session : Built-In Control Structures in Scala
Ayush Mishra
 
Scala Talk at FOSDEM 2009
Martin Odersky
 
Dynamic Python
Chui-Wen Chiu
 
Principles of functional progrmming in scala
ehsoon
 
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
Railroading into Scala
Nehal Shah
 
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Scala introduction
Yardena Meymann
 
Lecture 5: Functional Programming
Eelco Visser
 
Python idiomatico
PyCon Italia
 
Pydiomatic
rik0
 
Programming Android Application in Scala.
Brian Hsu
 
Introductiontoprogramminginscala
Amuhinda Hungai
 
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
Introduction to Scala
Aleksandar Prokopec
 
Ad

More from kao kuo-tung (13)

PDF
用 Open source 改造鍵盤
kao kuo-tung
 
PDF
Why is a[1] fast than a.get(1)
kao kuo-tung
 
PPTX
減少重複的測試程式碼的一些方法
kao kuo-tung
 
PDF
Openstack taskflow 簡介
kao kuo-tung
 
PDF
Async: ways to store state
kao kuo-tung
 
PDF
Openstack 簡介
kao kuo-tung
 
PDF
Docker 原理與實作
kao kuo-tung
 
PDF
那些年,我們一起看的例外
kao kuo-tung
 
PDF
Python 中 += 與 join比較
kao kuo-tung
 
PDF
Garbage collection 介紹
kao kuo-tung
 
PDF
Python 如何執行
kao kuo-tung
 
PDF
C python 原始碼解析 投影片
kao kuo-tung
 
PDF
recover_pdb 原理與介紹
kao kuo-tung
 
用 Open source 改造鍵盤
kao kuo-tung
 
Why is a[1] fast than a.get(1)
kao kuo-tung
 
減少重複的測試程式碼的一些方法
kao kuo-tung
 
Openstack taskflow 簡介
kao kuo-tung
 
Async: ways to store state
kao kuo-tung
 
Openstack 簡介
kao kuo-tung
 
Docker 原理與實作
kao kuo-tung
 
那些年,我們一起看的例外
kao kuo-tung
 
Python 中 += 與 join比較
kao kuo-tung
 
Garbage collection 介紹
kao kuo-tung
 
Python 如何執行
kao kuo-tung
 
C python 原始碼解析 投影片
kao kuo-tung
 
recover_pdb 原理與介紹
kao kuo-tung
 

Recently uploaded (20)

PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 

Python to scala

  • 2. 簡介 ● inwinSTACK ● Openstack contributor ○ Openstack Kolla core member ● kjellytw at gmail dot com ● http://www.blackwhite. tw/
  • 3. Java to Scala ● Java to Scala
  • 4. Python ● Object-oriented, ● Imperative ● Dynamic type ● Interpreted languages ● Support shell
  • 5. Scala ● Functional programming ● Static type ● Object-oriented ● Type inference ● Lazy (non-strict) evaluation ● Compiled languages ● Support shell
  • 6. python vs scala ● statement, expression. ● a + b => a.__add__ (b) ● f(a,b) => f.__call__ (a,b) ● everything "evaluates" to a value. ● a + b => a.+(2) ● f(a,b) => f.apply(a, b)
  • 7. variable - python vs scala a = 1 ● The return value of expression is `()`. var a = 1 var a: Int = 1
  • 8. const - python vs scala ● python doesn’t support const. ● The return value of expression is `()`. val a = 1 val a: Int = 1
  • 9. lazy ● Not support in native python. (Maybe some library support it. ● Initialization is deferred until it is accessed for the first time ● Check whether the value has already been initialized before a lazy value is accessed.
  • 10. lazy ● lazy var words = scala.io.Source.fromFile ("/usr/share/dict/words").mkString ● lazy val fibs: Stream[BigInt] = BigInt(0) #:: BigInt(1) #:: fibs.zip(fibs.tail).map { n => n. _1 + n._2 }
  • 11. if-else ● statement if a > 5: print(a) else: print() ● expression val x = if(a>5) {1} else 2 val y = if(1!=1) 1 //y == ()
  • 12. while while a > 5: print(a) a -= 1 ● The return value of expression is `()`. while ( a > 5) { print(a) a -= 1 }
  • 13. def loop(x: Int, xs: List[Int]): Int = { var max_value = x var rest = xs while (rest != Nil) { if (max_value < rest.head) max_value = rest. head rest = rest.tail } max_value
  • 14. tail recursion def loop(lst: List[Int], maxValue: Int): Int = lst match { case Nil => maxValue case x :: xs => if (x > maxValue) loop(xs, x) else loop(xs, maxValue) }
  • 15. tail recursion def max(lst: List[Int]): Int = { lst match { case Nil => 0 case x :: xs => loop(xs, x) } }
  • 16. tail recursion ● a tail call might lead to the same subroutine being called again later in the call chain. ● a tail recursive function is transformed into a loop by the compiler. ● use `@tailrec`
  • 17. do while ● Not support do { println(a) a -= 1 while( a > 5)
  • 18. for
  • 19. list comprehension vs for yield python scala: the syntax is similar with for.
  • 20. generator vs stream They are not the same. But they are similar in some case.
  • 21. function ● You can define many function with the same name. But only the function which is executed in last time will be called. ● Support overloading
  • 22. scala function def func(a: Int, b: Int) :Unit = { 1 }
  • 23. scala function 1. def fun = 1 // for pure function 2. def fun() {println(“S”)} # for side effect
  • 24. function argument ● support variable- length argument, keyworded argumen, default argument. ● support variable- length argument, default argument, call-by-name argument.
  • 25. variable-length , keyworded , default argument def func(a, b=1, *args, **kwargs): pass def func(a: Int, b: Int = 1, args: Int*) = { 1 }
  • 26. call-by-name argument ● python doesn’t support call-by-name. ● def mywhile(condition: => Boolean, body: => Unit)
  • 27. def mywhile(condition: => Boolean, body: => Unit): Int = { def loop(count: Int): Int = { if (condition) { body; loop(count + 1) } else count } loop(0) }
  • 28. var a = 1 print(mywhile({ a < 5 }, { a += 1 }))
  • 29. function return ● use `return` if you want to return something. ● if there are no return in function body, it will return `None`. ● avoid to use `return` keyword. ● if there are no return in function body, it will return the value of the last expression
  • 30. match-case ● python doesn’t support match-case.
  • 31. match-case x.asInstanceOf[Any] match { case x :: xs => println(x) case (a, b, c) => println(a) case p @ Some(v) if v == 2 => println(p) case x: Int if x != 2 => println(x) case _ => println(“None”) }
  • 32. class 1. multi inheritance 2. public 3. Not support overloading 1. single inheritance 2. public, protect, private 3. Support overloading
  • 33. class constructor class My(object): def __init__(self, x): self.x = x self.odd = x%2 ==0 def print_x(self): print(self.x) class My(var x: Int) { var odd = x % 2 ==0 def print_x() { println(x) } }
  • 34. scala auxiliary constructor class Length(val length: Int) { def this(str: String) { this(str.length) } def this(list: List[Any]) { this(list.length) } } new Length(5) new Length(“Hi”) new Length(List(1,2))
  • 35. duck typing class Length1(val length: Int) { def this(o: {def length:Int}) { this(o.length) } } ● All thing is duck typing in python. ● scala support duck typing.
  • 36. scala companion object ● singleton object ● companion object
  • 37. Singleton object object Main { def sayHi() { println("Hi!"); } }
  • 38. companion object class Main { def sayHelloWorld() { println("Hello World"); } } object Main { def sayHi() { println("Hi!"); } method,used for instance static method, used for class
  • 39. How to create instance? class A(object):pass a = A() class A {} val a = new A class B{} object B{def apply() = new B} val bB = B() Python Scala
  • 40. Type checking and cast 1. isinstance(a, str) 2. issubclass(A, object) 3. a.__class__ 1. "S".isInstanceOf[String] 2. 3. 4. "S".asInstanceOf [String]
  • 41. Type checking and cast if isinstance(a, int): print(“int”) elif isinstance(a, str): print(“str”) a mtach { case _: Int => println(“int”) case _: String => println(“Str”) }
  • 42. class inheritance ● Method Resolution Order ● class X(A, B):pass ● X.__mro__ ● single inheritance ● need `override` when overriding ● class X extends Any
  • 43. scala trait ● trait is like java interface but allows concrete implementations. ● class A extends B with C with D ○ extends + class|trait ○ with + trait
  • 44. case class ● python doesn’t support case class. ● case class generate the following method: ○ equals ○ apply for companion object . ○ unapply for companion object.
  • 45. Why we need case class? def Person(object): def __init__(self, name, age): self.name = name self.age = age person = Person(“bill”, 5)
  • 46. Why we need case class? case class Person(var name:String, var age:Int) val person = Person(“Bill”, 5)
  • 47. More case calss person match { case Person(name, age) if name == "X" => s"$name,$age" case _ => "Nothing" }
  • 50. package ● folder with `__init__.py` file ● package com.abc. name
  • 51. import ● the way to use the code in other file. ● use short name
  • 52. import ● the way to use the code in other file. ● use short name
  • 53. Implicit ● python doesn’t support implicit. ● Implicit Conversions ○ implicit defwrapString(s: String): WrappedString ● Implicit Parameters ○ implicit val n: Int = 5 ○ def add(x: Int)(implicit y: Int) = x + y ● more thing ...
  • 54. Scala type parameters ● List[String](); def drop1[A](l: List[A]) = l.tail
  • 55. Scala type parameters ● List[String](); def drop1[A](l: List[A]) = l.tail ● more thing about: ○ Bounds -> def biophony[T <: Animal] ○ Quantification -> def count(l: List[_]) = l.size ○ Variance
  • 56. Int ● int, long ● nerver overflow ● Int(32-bit signed) or Long(64-bit signed) or BigInt ● BitInt supports +,%,* ● care for overflow
  • 57. Boolean ● True and False ● False or True ● not True ● true && false ● true || false ● !true ● short-circuit
  • 58. String ● no char ● one line string: ○ “string” ○ ‘string’ ● multiline string: ○ “””dddd””” ○ ‘’’ccc’’’ ○ “abcd”[1] ● char => ‘c’ ● string => “c” ● “abcd”(1)
  • 59. String format ● "%s %d" % ("Hi", 5) ● '{0}'.format('a') ● 'Coordinates: {latitude}'.format (latitude='37.24N',) ● i"{names}" #P0510 ● "%s".format (firstName) ● s"Hello, $name"
  • 60. List in python vs ArrayBuffer in scala 1. List(1, 2, 3, 4) 2. [1, 2, 3, 4] 3. a[3] 4. a[-1] 5. a[1:-1] 6. a[1:-1:-1] 7. a[1] = 1 1. ArrayBuffer(1,2,3,4) 2. new ArrayBuffer[Int]() 3. a(3) 4. 5. a.slice(1, a.length-1) 6. 7. a(1) = 1
  • 61. List in python vs ArrayBuffer in scala 1. map(a, lambda x: x+1) 2. b = [i + 1 for i in a if i % 2 ==0] 1. a.map(_ + 1) 2. val b = for(i <- a if i % 2 ==0) yield i + 1
  • 62. a.map(x:Int => {x + 1}) a.map(x => {x+1}) a.map(x => x+ 1) a.map(_ + 1)
  • 63. List in python vs ArrayBuffer in scala 1. a.__getitem__ 2. a.__setitem__ 1. a.apply 2. a.update
  • 65. Scala List ● Linked list ● Optimal for last-in-first-out (LIFO), stack- like access patterns ● Immutable ● `Nil` means empty list.
  • 66. Scala List ● List(1, 2, 3) ● 1 :: 2 :: 3 :: Nil ● Nil.::(3).::(2).::(1)
  • 67. Scala List def max(lst: List[Int]): Int = { lst match { case Nil => 0 case x :: xs => loop(xs, x) } }
  • 68. Scala Async Future.apply[T](body: ⇒ T)(implicit executor: ExecutionContext): Future[T]
  • 69. def combined: Future[Int] = async { val future1 = slowCalcFuture val future2 = slowCalcFuture await(future1) + await(future2) }
  • 70. val future1 = slowCalcFuture val future2 = slowCalcFuture def combined: Future[Int] = for { r1 <- future1 r2 <- future2 } yield r1 + r2
  • 71. django vs play framework2 ● python web framework ● MVT ● support ORM ● scala/java web framework ● MVC ● support type checking in views.
  • 72. django class-based views vs play controller def index = Logging { Action { Ok("Hello World") } } class MyView(TemplateView): template_name = "about.html" Play Django
  • 73. django template vs play view
  • 74. play view ● type checking ● view as function. ○ views.html.list(List (“1”)) function argument function body call main function list.scala.html
  • 75. django forms vs play forms
  • 76. Thank you The slide will update continuously.