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

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

What's hot (20)

Building a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGLBuilding a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGL
 
Runtime Bytecode Transformation for Smalltalk
Runtime Bytecode Transformation for SmalltalkRuntime Bytecode Transformation for Smalltalk
Runtime Bytecode Transformation for Smalltalk
 
Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹Kotlin Receiver Types 介紹
Kotlin Receiver Types 介紹
 
PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...
PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...
PyParis2017 / Function-as-a-service - a pythonic perspective on severless com...
 
Kotlin Overview
Kotlin OverviewKotlin Overview
Kotlin Overview
 
C++ Generators and Property-based Testing
C++ Generators and Property-based TestingC++ Generators and Property-based Testing
C++ Generators and Property-based Testing
 
What make Swift Awesome
What make Swift AwesomeWhat make Swift Awesome
What make Swift Awesome
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before Reacting
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
 
Joblib for cloud computing
Joblib for cloud computingJoblib for cloud computing
Joblib for cloud computing
 
Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 
Kotlin presentation
Kotlin presentation Kotlin presentation
Kotlin presentation
 
Reactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScriptReactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScript
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Halogen: Past, Present, and Future
Halogen: Past, Present, and FutureHalogen: Past, Present, and Future
Halogen: Past, Present, and Future
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
MTL Versus Free
MTL Versus FreeMTL Versus Free
MTL Versus Free
 
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017Simple ETL in python 3.5+ with Bonobo - PyParis 2017
Simple ETL in python 3.5+ with Bonobo - PyParis 2017
 
Lua Study Share
Lua Study ShareLua Study Share
Lua Study Share
 

Viewers also liked

How to integrate python into a scala stack
How to integrate python into a scala stackHow to integrate python into a scala stack
How to integrate python into a scala stackFliptop
 
Immutable infrastructure 介紹與實做:以 kolla 為例
Immutable infrastructure 介紹與實做:以 kolla 為例Immutable infrastructure 介紹與實做:以 kolla 為例
Immutable infrastructure 介紹與實做:以 kolla 為例
kao kuo-tung
 
Python y Flink
Python y FlinkPython y Flink
Python y Flink
Paradigma Digital
 
Introduction to scala for a c programmer
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmerGirish Kumar A L
 
Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)
Denny Lee
 
Apache hive
Apache hiveApache hive
Apache hive
pradipbajpai68
 
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Databricks
 
Communication between Java and Python
Communication between Java and PythonCommunication between Java and Python
Communication between Java and Python
Andreas Schreiber
 
Openstack swift, how does it work?
Openstack swift, how does it work?Openstack swift, how does it work?
Openstack swift, how does it work?
kao kuo-tung
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable Language
Mario Gleichmann
 
Neural networks with python
Neural networks with pythonNeural networks with python
Neural networks with python
Simone Piunno
 
Intorduce to Ceph
Intorduce to CephIntorduce to Ceph
Intorduce to Ceph
kao kuo-tung
 
Indexed Hive
Indexed HiveIndexed Hive
Indexed Hive
NikhilDeshpande
 
Fun[ctional] spark with scala
Fun[ctional] spark with scalaFun[ctional] spark with scala
Fun[ctional] spark with scala
David Vallejo Navarro
 
Scala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsScala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and Implementations
MICHRAFY MUSTAFA
 
Scala eXchange: Building robust data pipelines in Scala
Scala eXchange: Building robust data pipelines in ScalaScala eXchange: Building robust data pipelines in Scala
Scala eXchange: Building robust data pipelines in Scala
Alexander Dean
 
Hive User Meeting August 2009 Facebook
Hive User Meeting August 2009 FacebookHive User Meeting August 2009 Facebook
Hive User Meeting August 2009 Facebook
ragho
 
DataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL WorkshopDataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL Workshop
Hakka Labs
 

Viewers also liked (20)

How to integrate python into a scala stack
How to integrate python into a scala stackHow to integrate python into a scala stack
How to integrate python into a scala stack
 
Immutable infrastructure 介紹與實做:以 kolla 為例
Immutable infrastructure 介紹與實做:以 kolla 為例Immutable infrastructure 介紹與實做:以 kolla 為例
Immutable infrastructure 介紹與實做:以 kolla 為例
 
Python y Flink
Python y FlinkPython y Flink
Python y Flink
 
Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012
 
Introduction to scala for a c programmer
Introduction to scala for a c programmerIntroduction to scala for a c programmer
Introduction to scala for a c programmer
 
Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)Jump Start into Apache Spark (Seattle Spark Meetup)
Jump Start into Apache Spark (Seattle Spark Meetup)
 
Apache hive
Apache hiveApache hive
Apache hive
 
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
Performance Optimization Case Study: Shattering Hadoop's Sort Record with Spa...
 
Communication between Java and Python
Communication between Java and PythonCommunication between Java and Python
Communication between Java and Python
 
Openstack swift, how does it work?
Openstack swift, how does it work?Openstack swift, how does it work?
Openstack swift, how does it work?
 
Piazza 2 lecture
Piazza 2 lecturePiazza 2 lecture
Piazza 2 lecture
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable Language
 
Neural networks with python
Neural networks with pythonNeural networks with python
Neural networks with python
 
Intorduce to Ceph
Intorduce to CephIntorduce to Ceph
Intorduce to Ceph
 
Indexed Hive
Indexed HiveIndexed Hive
Indexed Hive
 
Fun[ctional] spark with scala
Fun[ctional] spark with scalaFun[ctional] spark with scala
Fun[ctional] spark with scala
 
Scala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and ImplementationsScala: Pattern matching, Concepts and Implementations
Scala: Pattern matching, Concepts and Implementations
 
Scala eXchange: Building robust data pipelines in Scala
Scala eXchange: Building robust data pipelines in ScalaScala eXchange: Building robust data pipelines in Scala
Scala eXchange: Building robust data pipelines in Scala
 
Hive User Meeting August 2009 Facebook
Hive User Meeting August 2009 FacebookHive User Meeting August 2009 Facebook
Hive User Meeting August 2009 Facebook
 
DataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL WorkshopDataEngConf SF16 - Spark SQL Workshop
DataEngConf SF16 - Spark SQL Workshop
 

Similar to Python to scala

Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaAyush Mishra
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
Nehal Shah
 
Scala introduction
Scala introductionScala introduction
Scala introduction
Yardena Meymann
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
rik0
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
PyCon Italia
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
Brian Hsu
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
Amuhinda Hungai
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Aleksandar Prokopec
 

Similar to Python to scala (20)

Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
Scala
ScalaScala
Scala
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 

More from kao kuo-tung

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

More from kao kuo-tung (13)

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

Recently uploaded

Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 

Recently uploaded (20)

Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 

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.