SlideShare a Scribd company logo
Scala 2.8への移行
         へ
• ScalaAPI
  – 2.8
    • http://www.scala-
      lang.org/archives/downloads/distrib/files/nightly/do
      cs/library/index.html
  – 2.7
    • http://www.scala-lang.org/docu/files/api/index.html
  – sbazでローカルにダウンロード
    • > sbaz install scala-devel-docs
          – $SCALA_HOME/docs

• ソースリポジトリ
  – http://www.scala-lang.org/node/213
  – http://lampsvn.epfl.ch/trac/scala/browser/scala
• Java5以降に対応

• 余談:Java1.4を捨ててソースがすっきり。
 – 例:String#format
   • 2.7:
      – http://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_
        7_7_RC1/src/library/scala/runtime/RichString.scala


   • 2.8:
      – http://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/src/li
        brary/scala/collection/immutable/StringLike.scala
へ移行する際の注意点
Scala 2.8へ移行する際の注意点
• ~Web Flavorの場合~
             の場合~
  – http://d.hatena.ne.jp/kmizushima/20100223/1
    266940545

  – を読んで勉強させていただきました。

• Web Flavor (@keisuke_nさん作)
  – http://webflavor.sourceforge.net/index_ja.html
内側のパッケージから外側のパッケージのクラスを暗黙に利用


2.7
package foo
class Foo {
}

package foo.bar

class Bar {
  val f = new Foo //上位のパッケージはimportがいらない
}
内側のパッケージから外側のパッケージのクラスを暗黙に利用

2.8
package foo
class Foo {
}

package foo.bar
import foo.Foo
class Bar {
  val f = new Foo
}
//または、
package foo.bar
class Bar {
  val f = new _root_.foo.Foo
}
内側のパッケージから外側のパッケージのクラスを暗黙に利用

2.8
package foo
class Foo {
}

package foo {
 package bar {
    class Bar {
      val f = new Foo //外側のパッケージは参照できる
    }
  }
}
内側のパッケージから外側のパッケージのクラスを暗黙に利用

2.8
package foo {
  class Foo {
  }
  package bar {
    class Bar {
      val f = new Foo
    }
  }
}

    パッケージは入れ子構造で内側<->外側という捉え方
    パッケージは入れ子構造で内側   外側
内側のパッケージから外側のパッケージのクラスを暗黙に利用している場合

2.8の新文法
package foo
class Foo {
}

package foo
package bar
class Bar {
  val f = new Foo
}
型に注意
Seq型に注意

2.8
import scala.collection.mutable._

class Some {
 val list = new ListBuffer[Int] //mutableなリストが必要
 val seq = Seq(1,2,3,4)         //immutableのつもり・・

    seq.foreach( i => list.append(i) )

    seq.update(2, 7)          //うっかりseqを破壊
                               // (2.7ならコンパイルエラー)
}
型に注意
Seq型に注意

2.8
import scala.collection.mutable.{Seq=>_ , _ }

class Some {
 val list = new ListBuffer[Int] //mutableなリストが必要
 val seq = Seq(1,2,3,4)         //immutable

    seq.foreach( i => list.append(i) )

    seq.update(2, 7)          //コンパイルエラー
}
型に注意
Seq型に注意

2.8
//importした要素に別名をつける機能
import scala.collection.
  mutable.{Seq=>S ,ListBuffer=>LB, _ }

最後の_は、"残り全部"


//を利用したSeqの読み捨て(?)
import scala.collection.mutable.{Seq=>_ , _ }
配列と
配列とSeqの組み合わせに注意
      の組み合わせに注意

2.7
scala> val some = if( 1 > 0 ) Array(1,2,3) else Seq(1,2,3)
some: Seq[Int] = Array(1, 2, 3)

ArrayはSeqのサブタイプ



2.8
scala> val some = if( 1 > 0 ) Array(1,2,3) else Seq(1,2,3)
java.lang.ClassCastException: [I cannot be cast to scala.ScalaObject

scala> val some = if( 1 < 0 ) Array(1,2,3) else Seq(1,2,3)
some: ScalaObject = List(1, 2, 3)

                 型と同等になった。
ArrayはJavaの T[ ] 型と同等
          の

                                         ※でもAnyRefとかになってもよくね?
配列と
配列とSeqの組み合わせに注意
      の組み合わせに注意

2.8
scala> val some:Seq[Int] = if( 1 > 0 ) Array(1,2,3) else Seq(1,2,3)
some: Seq[Int] = Array(1, 2, 3)

scala> some.getClass
res13: class scala.collection.mutable.WrappedArray$ofInt

型を明示すれば implicit conversionが働く。
Predef.wrapArrayを参照
コレクションクラスの継承に注意
コレクションクラスの継承に注意
          継承

これはもうどうしようもないので
頑張りましょう。
によるメソッドオーバーローディング
implicit conversionによるメソッドオーバーローディング

 2.7             List.findはAPI上に既に存在するメソッドであることに注意!

 scala> class RichListString(xs: List[String]) {
  def find(x: String) = xs.find{_ == x} //(1) こっちはOK
  def find(x: String, dummy: String) = xs.find{_ == x} //(2) 2.8ではこれがダメ
 }
 implicit def enrich(xs: List[String]): RichListString = new RichListString(xs)
 List("A", "B", "C").find("A", "c")

 res2: Option[String] = Some(A)

 2.8
 scala> List("A", "B", "C").find("A", "c")

 error: too many arguments for method find:

 List.findメソッドはAPIに既に存在しているために解決に失敗。
 逆に(1)が動いてしまうのが微妙なところ。
 >同名メソッドをimplicit定義するのは避ける
誤解のないように・・・・


2.8     こういうのは全然OK
class RichListString(xs: List[String]) {
 def firstElem() = xs.head
 def firstElem(n:Int) = xs.head + n
 def firstElem(n:Int,m:Int) = xs.head + n + m
}
Scala2.8への移行
Scala2.8への移行
へ移行する際の注意点
Scala 2.8へ移行する際の注意点
       アプリの場合~
• ~Liftアプリの場合~
       アプリ

 – 弊社プロジェクトのLiftアプリケーションを
   Scala2.8でコンパイル。

 – エラーやWarningが出た箇所をご報告。

 – 業務Webアプリなので、さほど込み入ったことは
   していない。
Lift2.0をScala2.8で動かすには・・・・


mvn archetype:generate -U -DarchetypeGroupId=net.liftweb ¥
-DarchetypeArtifactId=lift-archetype-basic ¥
-DarchetypeVersion=2.0-scala280-SNAPSHOT ¥
-DarchetypeRepository=http://scala-tools.org/repo-snapshots ¥
-DremoteRepositories=http://scala-tools.org/repo-snapshots ¥
-DgroupId=yours -DartifactId=yourapp


Scalaバージョンには"2.8.0.Beta1"を入力




                                Simple Build Toolで動かすには
                               http://blog.takeda-soft.jp/blog/show/369
メモリを調整しておくと良いかも
pom.xml に追加
<plugin>
    <groupId>org.scala-tools</groupId>
    <artifactId>maven-scala-plugin</artifactId>
    <executions>
       <execution>
          <id>scala-compile</id>
       </execution>
    </executions>
    <configuration>
      <jvmArgs>
        <jvmArg>-Xmx256m</jvmArg>
        <jvmArg>-Xss1024K</jvmArg>
        <jvmArg>-XX:PermSize=64m</jvmArg>
      </jvmArgs>
    </configuration>
</plugin>
SHtml (ガクブルな仕様変更)

class AForm {

    object name extends RequestVar[String](S.param("name").openOr(""))

    def add(xhtml: NodeSeq):NodeSeq = {
       bind("f", xhtml,
          "name" -> SHtml.text( name.is, name = _ ) ,
          "submit" -> SHtml.submit("送信", doAdd) )
     }
}


Re: Scala 2.8 Eclipse plugin beta - compilation errors in Lift
There is a change to type inferencing in 2.8.
The construct:
 SHtml.text( hours, hours = _ )
No longer seems compiler-friendly. Try:
 SHtml.text( hours, x => hours = x )

                                        ※ Exploring Liftのサンプルには多い記述方法
SHtml

class AForm {

    object name extends RequestVar[String](S.param("name").openOr(""))

    def add(xhtml: NodeSeq):NodeSeq = {
       bind("f", xhtml,
          "name" -> SHtml.text( name.is, name(_) ) , // (x)=>name(x)の糖衣
          "submit" -> SHtml.submit("送信", doAdd) )
     }
}

               この書き方で統一していたので助かった ;x;
          ただ、なんでこっちだと助かったのかはわからない。。
AnyVar / MappedField からのimplicit conversion

class AForm {
 object price extends RequestVar[String](S.param("price").openOr("0"))

 def doAdd() {
   val charge = ShippingCharge.find(1).charge //DBからカラムを取得

    Order.create.totalPrice( price.toInt + charge ).save
  }
} // Scala2.7では、良きに計らってくれてた

class AForm {
 object price extends RequestVar[String](S.param("price").openOr("0"))

 def doAdd() {
   val charge = ShippingCharge.find(1).charge //DBからカラムを取得

    Order.create.totalPrice( price.is.toInt + charge.is ).save
  }
} // Scala2.8では、コンパイルエラー。
  // 「is」を明示。Convert the field to its "context free" type
Collection のAPI変更(deprecatedが多い)

Seq.first (のサブクラス全部)

-> IterableLike.head

//aliasが張られているだけ。
@deprecated("use `head' instead") def first: A = head



Map.keys / values

-> MapLike.keysIterator / valuesIterator

//alias
@deprecated("use `valuesIterator' instead")
  def values: Iterator[B] = valuesIterator
Collection のAPI変更(deprecatedが多い)

List.sort( (A,A) => Boolean )

-> SeqLike.sortWith( (A,A) => Boolean )

List.sortはまだ独自ロジックが残っているので注意。
こんなコメントが残ってる!
!!! todo: move sorting to IterableLike


傾向:
 ○○Likeクラスにメソッドをまとめて、
 各CollectionではそれらをMix-inする形に統合している。

 たいていコンパイル時にdeprecated警告が出て、
 代替メソッドを丁寧に表示してくれるので比較的安心。

 deprecatedが出た場合は、実装を覗いてみるとなお安心。
へ移行する際の注意点
Scala 2.8へ移行する際の注意点


       東北アーカイブ編
• Scala東北アーカイブ編

 – 2.8の新機能についてのトピックを紹介します。
Scala東北MLより
• Traversable#withFilter
  – http://groups.google.co.jp/group/scala--
    tohoku/browse_thread/thread/3a12002a643b
    959f?hl=ja
• else の無い if 式の型
  – http://groups.google.co.jp/group/scala--
    tohoku/browse_thread/thread/c737c1940441d
    2b0?hl=ja
勉強会@東北
• Scala勉強会@東北
 – Changes and Improvements on Scala 2.8
    • http://sites.google.com/site/scalatohoku/changes-
      and-improvements-on-scala-2-8
• 抜粋
    •   Redesigned collection libraries
    •   Named and default arguments
    •   Support for continuations
    •                      (                       )
        Type specialization(@specialized annotation)
    •   @tailrec and @switch


• 山中さん素晴らしいっっ
新機能-Scala東北ML
• scala.reflect.Manifest
   – http://groups.google.co.jp/group/scala--
     tohoku/browse_thread/thread/2858a1b7807929c5?hl
     =ja
• scala.util.control.Breaks
   – http://groups.google.co.jp/group/scala--
     tohoku/browse_thread/thread/f4475f1d0da0181f?hl=j
     a
• パターンマッチの最適化のチェック(@tailrec)
   – http://groups.google.co.jp/group/scala--
     tohoku/browse_thread/thread/ac3da34f805ee6c2?hl=
     ja
新機能-Scala東北ML
• 自己末尾再帰関数呼び出しの最適化
  – http://groups.google.co.jp/group/scala--
    tohoku/browse_thread/thread/6af4efd83a8e0
    328?hl=ja
• case class - copy メソッド
  – http://groups.google.co.jp/group/scala--
    tohoku/browse_thread/thread/72211849f32aa
    5e4?hl=ja
Scala2.8新機能を追う

追ってぜひみんなに教えてください m(_ _)m
A Taste of 2.8
• Scala Collections
  – http://www.scala-lang.org/node/2060
• Named and Default Arguments
  – http://www.scala-lang.org/node/2075
• Continuations
  – http://www.scala-lang.org/node/2096
• The Interactive Interpreter (REPL)
  – http://www.scala-lang.org/node/2097
Scala2.8から
     体系的に勉強したい人へ

• Oreilly:Programming Scala
  – http://programming-scala.labs.oreilly.com/
言語仕様の一次情報

• Scala Reference
   – sbaz install scala-documentation

• The Scala Language Specification Version 2.8
   – ChangeLogより抜粋
•   Changes in Version 2.8.0
     – Trailing commas
          • Trailing commas in expression, argument, type or pattern sequences are no longer
            supported.


•   Changes in Version 2.8 (under development)
     – Changed visibility rules for nested packages (where done?)
     – Changed visibility rules in §2 so that packages are no longer treated specially.
     – Added section §3.5.3 on weak conformance. Relaxed type rules for
       conditionals,match expressions, try expressions to compute their result type
       using least upper bound wrt weak conformance. Relaxed type rule for local type
       inference so that argument types need only weekly conformto inferred formal
       parameter types. Added section on numeric widening in §6.25 to support weak
       conformance.
     – Tightened rules to avpod (avoidのtypo?) accidential overrides in §5.1.4.
     – Removed class literals.
     – Added section §7.4 on context bounds.
     – Clarified differences between isInstanceOf and pattern matches (§12.1).
     – Allowed implicit modifier on function literals with a single parameter (§6.23).
の確認
                     Change Logの確認

• Trailing commas
   – List(1,2,3,) // 2.7 ではOKだけど、2.8ではコンパイルエラー

• Weak Conformance
  – List( 1, 1.0 )
      • 2.7では List[AnyVal] = List( 1, 1.0 )
      • 2.8では List[Double] = List( 1.0, 1.0 ) //
の確認
                       Change Logの確認

                (???)
• Context Bounds(???)
  – 2.7
     •   class Animal
     •   class Dog[T]
     •   implicit object dog extends Dog[Animal]
     •   class Monkey[T]( implicit dog:Dog[T] )
     •   new Monkey[Animal]

  – 2.8
     •   class Animal
     •   class Dog[T]
     •   implicit object dog extends Dog[Animal]
     •   class Monkey[T:Dog]
     •   new Monkey
にはないが追記されてること
      Change Logにはないが追記されてること
• 3.7 Type Erasure
   – compound typeのerasureについて
• 4.3 Type Declarations and Type Aliases
   – Example 4.3.2 Pair をTuple2のAliasとして定義してる例
                               の     として定義してる例
• 4.6 Function Declarations and Definition の最後の節
• 5.1.1 Constructor Invocations
   – 6.6.1 Named Parameter に関連して追記
• 5.3.2 Case Classes
         メソッド追記
   – copyメソッド追記
• 6.6 Function Applications
   – call-by-name/call-by-value のくだり変更
• 6.6.1 Named and Default Arguments 追記
• 6.20 Return Expressions
     内部無名関数からのreturnの挙動
   – 内部無名関数からの      の挙動
にはないが追記されてること
       Change Logにはないが追記されてること
• 6.23 Anonymouse Functions
     無名関数でNamed Parameterをimplicitにしたときの挙動
   – 無名関数で               を        にしたときの挙動
• 6.25 Implicit Conversions
   – Numeric Widening (Weak Conformするときの変換について)
• 6.25.3 Overloading Resolution
   – よくわからないけど、記述が大幅に変わってます><
• 7.5 Manifests
   – To be written..
• 8.1.3 Pattern Binders
• 8.1.8 Extractor Patterns
   – Example 8.1.3 追記
• Chapter11 User-Defined Annotations
                  の      定義が削除
   – NameValuePairのSyntax定義が削除
ブログなど
• Bay-Area Scala Enthusiasts (BASE)
  Meeting: What's New In Scala 2.8
  – http://blog.objectmentor.com/articles/2009/06/
    05/bay-area-scala-enthusiasts-base-meeting-
    whats-new-in-scala-2-8
• Control flows in Heaven with Scala 2.8
  continuations
  – http://ahardcodersday.blogspot.com/2009/08/
    control-flows-in-heaven-with-scala-28.html
  – http://ahardcodersday.blogspot.com/2009/08/
    control-flows-in-heaven-with-scala-28_27.html

More Related Content

PDF
Scala2.8への移行
PDF
rpscala35-scala2.9.0
PDF
Best practice laravel
PDF
Scala EE 7 Essentials
PDF
Phantom Type in Scala
PPTX
Java8勉強会
PDF
社内Java8勉強会 ラムダ式とストリームAPI
PDF
Scalaノススメ
Scala2.8への移行
rpscala35-scala2.9.0
Best practice laravel
Scala EE 7 Essentials
Phantom Type in Scala
Java8勉強会
社内Java8勉強会 ラムダ式とストリームAPI
Scalaノススメ

What's hot (19)

PDF
BOF1-Scala02.pdf
PPT
Rpscala2011 0601
PDF
JavaScript (ECMAScript) 2013
PDF
Scala の関数型プログラミングを支える技術
PDF
Java8のstreamをダラダラまとめてみる
PPT
ジェネリクスの基礎と クラス設計への応用
PDF
はてなブックマーク in Scala
PDF
JavaのGenericsとは?
PDF
実務者のためのかんたんScalaz
PDF
What Dotty fixes @ Scala関西サミット
PDF
Move semantics
PDF
ALPSチュートリアル(7) アプリケーションのALPS化
PDF
from old Java to modern Java
PDF
Java SE 8 lambdaで変わる プログラミングスタイル
PDF
20150302 java8 第一回_ラムダ式(1)
PPTX
Scala勉強会
PDF
Scalaで萌える関数型プログラミング[完全版]
PDF
ALPSチュートリアル(2) ALPSのインストール
PDF
ScalaMatsuri 2016
BOF1-Scala02.pdf
Rpscala2011 0601
JavaScript (ECMAScript) 2013
Scala の関数型プログラミングを支える技術
Java8のstreamをダラダラまとめてみる
ジェネリクスの基礎と クラス設計への応用
はてなブックマーク in Scala
JavaのGenericsとは?
実務者のためのかんたんScalaz
What Dotty fixes @ Scala関西サミット
Move semantics
ALPSチュートリアル(7) アプリケーションのALPS化
from old Java to modern Java
Java SE 8 lambdaで変わる プログラミングスタイル
20150302 java8 第一回_ラムダ式(1)
Scala勉強会
Scalaで萌える関数型プログラミング[完全版]
ALPSチュートリアル(2) ALPSのインストール
ScalaMatsuri 2016
Ad

Viewers also liked (7)

PPT
Videodata Presentation Jan 2008
PDF
Business Process Management Succeeding With BPM
PDF
Accio Data: Collaborative projects using free tools
PPT
Pozycjonujemy W Google
PPT
Vision And Commitment Incpen
PPTX
Welcome! Accessible reference for a diverse community
Videodata Presentation Jan 2008
Business Process Management Succeeding With BPM
Accio Data: Collaborative projects using free tools
Pozycjonujemy W Google
Vision And Commitment Incpen
Welcome! Accessible reference for a diverse community
Ad

Similar to Scala2.8への移行 (20)

PDF
言語アップデート -Scala編-
PDF
ScalaでAndroidアプリ開発
PDF
Scalaでのプログラム開発
PDF
Scala conf2013
PDF
Scala超入門 - 2014/12/13 Scala関西勉強会
PPTX
明日から業務で使うScala
PDF
ATN No.2 Scala事始め
PDF
Scala is-unscared
PDF
こわくないScala
PPTX
ゼロから始めるScala文法 (再)
PDF
めんどくさくない Scala #kwkni_scala
PDF
Scalaプログラミング・マニアックス
PDF
プログラミング言語Scala
PPTX
関数型言語&形式的手法セミナー(3)
PDF
BOF1-Scala02.pdf
PDF
BOF1-Scala02.pdf
PDF
Play framework 2.0のおすすめと1.2からのアップグレード
PDF
Asakusa FrameworkとScalaの密かな関係
PDF
Scalaの現状と課題
PPT
Scala Daysに行ってみて
言語アップデート -Scala編-
ScalaでAndroidアプリ開発
Scalaでのプログラム開発
Scala conf2013
Scala超入門 - 2014/12/13 Scala関西勉強会
明日から業務で使うScala
ATN No.2 Scala事始め
Scala is-unscared
こわくないScala
ゼロから始めるScala文法 (再)
めんどくさくない Scala #kwkni_scala
Scalaプログラミング・マニアックス
プログラミング言語Scala
関数型言語&形式的手法セミナー(3)
BOF1-Scala02.pdf
BOF1-Scala02.pdf
Play framework 2.0のおすすめと1.2からのアップグレード
Asakusa FrameworkとScalaの密かな関係
Scalaの現状と課題
Scala Daysに行ってみて

Scala2.8への移行

  • 2. • ScalaAPI – 2.8 • http://www.scala- lang.org/archives/downloads/distrib/files/nightly/do cs/library/index.html – 2.7 • http://www.scala-lang.org/docu/files/api/index.html – sbazでローカルにダウンロード • > sbaz install scala-devel-docs – $SCALA_HOME/docs • ソースリポジトリ – http://www.scala-lang.org/node/213 – http://lampsvn.epfl.ch/trac/scala/browser/scala
  • 3. • Java5以降に対応 • 余談:Java1.4を捨ててソースがすっきり。 – 例:String#format • 2.7: – http://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_ 7_7_RC1/src/library/scala/runtime/RichString.scala • 2.8: – http://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/src/li brary/scala/collection/immutable/StringLike.scala
  • 4. へ移行する際の注意点 Scala 2.8へ移行する際の注意点 • ~Web Flavorの場合~ の場合~ – http://d.hatena.ne.jp/kmizushima/20100223/1 266940545 – を読んで勉強させていただきました。 • Web Flavor (@keisuke_nさん作) – http://webflavor.sourceforge.net/index_ja.html
  • 5. 内側のパッケージから外側のパッケージのクラスを暗黙に利用 2.7 package foo class Foo { } package foo.bar class Bar { val f = new Foo //上位のパッケージはimportがいらない }
  • 6. 内側のパッケージから外側のパッケージのクラスを暗黙に利用 2.8 package foo class Foo { } package foo.bar import foo.Foo class Bar { val f = new Foo } //または、 package foo.bar class Bar { val f = new _root_.foo.Foo }
  • 7. 内側のパッケージから外側のパッケージのクラスを暗黙に利用 2.8 package foo class Foo { } package foo { package bar { class Bar { val f = new Foo //外側のパッケージは参照できる } } }
  • 8. 内側のパッケージから外側のパッケージのクラスを暗黙に利用 2.8 package foo { class Foo { } package bar { class Bar { val f = new Foo } } } パッケージは入れ子構造で内側<->外側という捉え方 パッケージは入れ子構造で内側 外側
  • 10. 型に注意 Seq型に注意 2.8 import scala.collection.mutable._ class Some { val list = new ListBuffer[Int] //mutableなリストが必要 val seq = Seq(1,2,3,4) //immutableのつもり・・ seq.foreach( i => list.append(i) ) seq.update(2, 7) //うっかりseqを破壊 // (2.7ならコンパイルエラー) }
  • 11. 型に注意 Seq型に注意 2.8 import scala.collection.mutable.{Seq=>_ , _ } class Some { val list = new ListBuffer[Int] //mutableなリストが必要 val seq = Seq(1,2,3,4) //immutable seq.foreach( i => list.append(i) ) seq.update(2, 7) //コンパイルエラー }
  • 12. 型に注意 Seq型に注意 2.8 //importした要素に別名をつける機能 import scala.collection. mutable.{Seq=>S ,ListBuffer=>LB, _ } 最後の_は、"残り全部" //を利用したSeqの読み捨て(?) import scala.collection.mutable.{Seq=>_ , _ }
  • 13. 配列と 配列とSeqの組み合わせに注意 の組み合わせに注意 2.7 scala> val some = if( 1 > 0 ) Array(1,2,3) else Seq(1,2,3) some: Seq[Int] = Array(1, 2, 3) ArrayはSeqのサブタイプ 2.8 scala> val some = if( 1 > 0 ) Array(1,2,3) else Seq(1,2,3) java.lang.ClassCastException: [I cannot be cast to scala.ScalaObject scala> val some = if( 1 < 0 ) Array(1,2,3) else Seq(1,2,3) some: ScalaObject = List(1, 2, 3) 型と同等になった。 ArrayはJavaの T[ ] 型と同等 の ※でもAnyRefとかになってもよくね?
  • 14. 配列と 配列とSeqの組み合わせに注意 の組み合わせに注意 2.8 scala> val some:Seq[Int] = if( 1 > 0 ) Array(1,2,3) else Seq(1,2,3) some: Seq[Int] = Array(1, 2, 3) scala> some.getClass res13: class scala.collection.mutable.WrappedArray$ofInt 型を明示すれば implicit conversionが働く。 Predef.wrapArrayを参照
  • 15. コレクションクラスの継承に注意 コレクションクラスの継承に注意 継承 これはもうどうしようもないので 頑張りましょう。
  • 16. によるメソッドオーバーローディング implicit conversionによるメソッドオーバーローディング 2.7 List.findはAPI上に既に存在するメソッドであることに注意! scala> class RichListString(xs: List[String]) { def find(x: String) = xs.find{_ == x} //(1) こっちはOK def find(x: String, dummy: String) = xs.find{_ == x} //(2) 2.8ではこれがダメ } implicit def enrich(xs: List[String]): RichListString = new RichListString(xs) List("A", "B", "C").find("A", "c") res2: Option[String] = Some(A) 2.8 scala> List("A", "B", "C").find("A", "c") error: too many arguments for method find: List.findメソッドはAPIに既に存在しているために解決に失敗。 逆に(1)が動いてしまうのが微妙なところ。 >同名メソッドをimplicit定義するのは避ける
  • 17. 誤解のないように・・・・ 2.8 こういうのは全然OK class RichListString(xs: List[String]) { def firstElem() = xs.head def firstElem(n:Int) = xs.head + n def firstElem(n:Int,m:Int) = xs.head + n + m }
  • 20. へ移行する際の注意点 Scala 2.8へ移行する際の注意点 アプリの場合~ • ~Liftアプリの場合~ アプリ – 弊社プロジェクトのLiftアプリケーションを Scala2.8でコンパイル。 – エラーやWarningが出た箇所をご報告。 – 業務Webアプリなので、さほど込み入ったことは していない。
  • 21. Lift2.0をScala2.8で動かすには・・・・ mvn archetype:generate -U -DarchetypeGroupId=net.liftweb ¥ -DarchetypeArtifactId=lift-archetype-basic ¥ -DarchetypeVersion=2.0-scala280-SNAPSHOT ¥ -DarchetypeRepository=http://scala-tools.org/repo-snapshots ¥ -DremoteRepositories=http://scala-tools.org/repo-snapshots ¥ -DgroupId=yours -DartifactId=yourapp Scalaバージョンには"2.8.0.Beta1"を入力 Simple Build Toolで動かすには http://blog.takeda-soft.jp/blog/show/369
  • 22. メモリを調整しておくと良いかも pom.xml に追加 <plugin> <groupId>org.scala-tools</groupId> <artifactId>maven-scala-plugin</artifactId> <executions> <execution> <id>scala-compile</id> </execution> </executions> <configuration> <jvmArgs> <jvmArg>-Xmx256m</jvmArg> <jvmArg>-Xss1024K</jvmArg> <jvmArg>-XX:PermSize=64m</jvmArg> </jvmArgs> </configuration> </plugin>
  • 23. SHtml (ガクブルな仕様変更) class AForm { object name extends RequestVar[String](S.param("name").openOr("")) def add(xhtml: NodeSeq):NodeSeq = { bind("f", xhtml, "name" -> SHtml.text( name.is, name = _ ) , "submit" -> SHtml.submit("送信", doAdd) ) } } Re: Scala 2.8 Eclipse plugin beta - compilation errors in Lift There is a change to type inferencing in 2.8. The construct: SHtml.text( hours, hours = _ ) No longer seems compiler-friendly. Try: SHtml.text( hours, x => hours = x ) ※ Exploring Liftのサンプルには多い記述方法
  • 24. SHtml class AForm { object name extends RequestVar[String](S.param("name").openOr("")) def add(xhtml: NodeSeq):NodeSeq = { bind("f", xhtml, "name" -> SHtml.text( name.is, name(_) ) , // (x)=>name(x)の糖衣 "submit" -> SHtml.submit("送信", doAdd) ) } } この書き方で統一していたので助かった ;x; ただ、なんでこっちだと助かったのかはわからない。。
  • 25. AnyVar / MappedField からのimplicit conversion class AForm { object price extends RequestVar[String](S.param("price").openOr("0")) def doAdd() { val charge = ShippingCharge.find(1).charge //DBからカラムを取得 Order.create.totalPrice( price.toInt + charge ).save } } // Scala2.7では、良きに計らってくれてた class AForm { object price extends RequestVar[String](S.param("price").openOr("0")) def doAdd() { val charge = ShippingCharge.find(1).charge //DBからカラムを取得 Order.create.totalPrice( price.is.toInt + charge.is ).save } } // Scala2.8では、コンパイルエラー。 // 「is」を明示。Convert the field to its "context free" type
  • 26. Collection のAPI変更(deprecatedが多い) Seq.first (のサブクラス全部) -> IterableLike.head //aliasが張られているだけ。 @deprecated("use `head' instead") def first: A = head Map.keys / values -> MapLike.keysIterator / valuesIterator //alias @deprecated("use `valuesIterator' instead") def values: Iterator[B] = valuesIterator
  • 27. Collection のAPI変更(deprecatedが多い) List.sort( (A,A) => Boolean ) -> SeqLike.sortWith( (A,A) => Boolean ) List.sortはまだ独自ロジックが残っているので注意。 こんなコメントが残ってる! !!! todo: move sorting to IterableLike 傾向: ○○Likeクラスにメソッドをまとめて、 各CollectionではそれらをMix-inする形に統合している。 たいていコンパイル時にdeprecated警告が出て、 代替メソッドを丁寧に表示してくれるので比較的安心。 deprecatedが出た場合は、実装を覗いてみるとなお安心。
  • 28. へ移行する際の注意点 Scala 2.8へ移行する際の注意点 東北アーカイブ編 • Scala東北アーカイブ編 – 2.8の新機能についてのトピックを紹介します。
  • 29. Scala東北MLより • Traversable#withFilter – http://groups.google.co.jp/group/scala-- tohoku/browse_thread/thread/3a12002a643b 959f?hl=ja • else の無い if 式の型 – http://groups.google.co.jp/group/scala-- tohoku/browse_thread/thread/c737c1940441d 2b0?hl=ja
  • 30. 勉強会@東北 • Scala勉強会@東北 – Changes and Improvements on Scala 2.8 • http://sites.google.com/site/scalatohoku/changes- and-improvements-on-scala-2-8 • 抜粋 • Redesigned collection libraries • Named and default arguments • Support for continuations • ( ) Type specialization(@specialized annotation) • @tailrec and @switch • 山中さん素晴らしいっっ
  • 31. 新機能-Scala東北ML • scala.reflect.Manifest – http://groups.google.co.jp/group/scala-- tohoku/browse_thread/thread/2858a1b7807929c5?hl =ja • scala.util.control.Breaks – http://groups.google.co.jp/group/scala-- tohoku/browse_thread/thread/f4475f1d0da0181f?hl=j a • パターンマッチの最適化のチェック(@tailrec) – http://groups.google.co.jp/group/scala-- tohoku/browse_thread/thread/ac3da34f805ee6c2?hl= ja
  • 32. 新機能-Scala東北ML • 自己末尾再帰関数呼び出しの最適化 – http://groups.google.co.jp/group/scala-- tohoku/browse_thread/thread/6af4efd83a8e0 328?hl=ja • case class - copy メソッド – http://groups.google.co.jp/group/scala-- tohoku/browse_thread/thread/72211849f32aa 5e4?hl=ja
  • 34. A Taste of 2.8 • Scala Collections – http://www.scala-lang.org/node/2060 • Named and Default Arguments – http://www.scala-lang.org/node/2075 • Continuations – http://www.scala-lang.org/node/2096 • The Interactive Interpreter (REPL) – http://www.scala-lang.org/node/2097
  • 35. Scala2.8から 体系的に勉強したい人へ • Oreilly:Programming Scala – http://programming-scala.labs.oreilly.com/
  • 36. 言語仕様の一次情報 • Scala Reference – sbaz install scala-documentation • The Scala Language Specification Version 2.8 – ChangeLogより抜粋
  • 37. Changes in Version 2.8.0 – Trailing commas • Trailing commas in expression, argument, type or pattern sequences are no longer supported. • Changes in Version 2.8 (under development) – Changed visibility rules for nested packages (where done?) – Changed visibility rules in §2 so that packages are no longer treated specially. – Added section §3.5.3 on weak conformance. Relaxed type rules for conditionals,match expressions, try expressions to compute their result type using least upper bound wrt weak conformance. Relaxed type rule for local type inference so that argument types need only weekly conformto inferred formal parameter types. Added section on numeric widening in §6.25 to support weak conformance. – Tightened rules to avpod (avoidのtypo?) accidential overrides in §5.1.4. – Removed class literals. – Added section §7.4 on context bounds. – Clarified differences between isInstanceOf and pattern matches (§12.1). – Allowed implicit modifier on function literals with a single parameter (§6.23).
  • 38. の確認 Change Logの確認 • Trailing commas – List(1,2,3,) // 2.7 ではOKだけど、2.8ではコンパイルエラー • Weak Conformance – List( 1, 1.0 ) • 2.7では List[AnyVal] = List( 1, 1.0 ) • 2.8では List[Double] = List( 1.0, 1.0 ) //
  • 39. の確認 Change Logの確認 (???) • Context Bounds(???) – 2.7 • class Animal • class Dog[T] • implicit object dog extends Dog[Animal] • class Monkey[T]( implicit dog:Dog[T] ) • new Monkey[Animal] – 2.8 • class Animal • class Dog[T] • implicit object dog extends Dog[Animal] • class Monkey[T:Dog] • new Monkey
  • 40. にはないが追記されてること Change Logにはないが追記されてること • 3.7 Type Erasure – compound typeのerasureについて • 4.3 Type Declarations and Type Aliases – Example 4.3.2 Pair をTuple2のAliasとして定義してる例 の として定義してる例 • 4.6 Function Declarations and Definition の最後の節 • 5.1.1 Constructor Invocations – 6.6.1 Named Parameter に関連して追記 • 5.3.2 Case Classes メソッド追記 – copyメソッド追記 • 6.6 Function Applications – call-by-name/call-by-value のくだり変更 • 6.6.1 Named and Default Arguments 追記 • 6.20 Return Expressions 内部無名関数からのreturnの挙動 – 内部無名関数からの の挙動
  • 41. にはないが追記されてること Change Logにはないが追記されてること • 6.23 Anonymouse Functions 無名関数でNamed Parameterをimplicitにしたときの挙動 – 無名関数で を にしたときの挙動 • 6.25 Implicit Conversions – Numeric Widening (Weak Conformするときの変換について) • 6.25.3 Overloading Resolution – よくわからないけど、記述が大幅に変わってます>< • 7.5 Manifests – To be written.. • 8.1.3 Pattern Binders • 8.1.8 Extractor Patterns – Example 8.1.3 追記 • Chapter11 User-Defined Annotations の 定義が削除 – NameValuePairのSyntax定義が削除
  • 42. ブログなど • Bay-Area Scala Enthusiasts (BASE) Meeting: What's New In Scala 2.8 – http://blog.objectmentor.com/articles/2009/06/ 05/bay-area-scala-enthusiasts-base-meeting- whats-new-in-scala-2-8 • Control flows in Heaven with Scala 2.8 continuations – http://ahardcodersday.blogspot.com/2009/08/ control-flows-in-heaven-with-scala-28.html – http://ahardcodersday.blogspot.com/2009/08/ control-flows-in-heaven-with-scala-28_27.html