Skip to content

Instantly share code, notes, and snippets.

@kmizu
Last active August 25, 2017 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmizu/0c40557c3e2c11ed849b509263638069 to your computer and use it in GitHub Desktop.
Save kmizu/0c40557c3e2c11ed849b509263638069 to your computer and use it in GitHub Desktop.
KotlinプログラマのためのScala入門(1)〜基本編〜 ref: http://qiita.com/kmizu/items/9d16360c4d383f3fa2aa
val i = 1
println(i) // 1
i = i + 1 // コンパイルエラー
var j = 1
println(j) // 1
j = j + 1 // OK
println(j) // 2
val i = 1
println(i) // 1
i = i + 1 // コンパイルエラー
var j = 1
println(j) // 1
j = j + 1 // OK
println(j) // 2
sealed abstract class ParseResult[+T]
case class ParseSuccess[+T](value: T, next: String) extends ParseResult[T]
case class ParseFailure(message: String) extends ParseResult[Nothing]
val result: ParseResult[String] = ...
result match { // 通常、case classの中身をパターンマッチであらかじめ分解する
case ParseSuccess(v, n) =>
case ParseFailure(m) =>
}
sealed class ParseResult<out T> {
data class ParseSuccess<out T>(val value: T, val next: String): ParseResult<T>()
data class ParseFailure(val message: String): ParseResult<Nothing>()
}
val result: ParseResult<String> = ...
when(result) {
is ParseResult.ParseSuccess -> // result: ParseSuccess
is ParseResult.ParseFailure -> // result: ParseFailure
}
interface Foo {
fun foo() {
println("Foo")
}
}
trait Foo {
def foo(): Unit = {
println("Foo")
}
}
val s: String? = null
val s: String = "FOO"
val s: Option[String] = None
val s: String = "FOO"
val v = Integer.parseInt("100")
val v = Integer.parseInt("100")
val proc: () -> Int = { 1 }
val proc: () => Int = {() => 1}
val iLtj = if(i < j) "i < j" else "i >= j" // String
val x: Any = "FOO"
if(x is String) {
// x はこの中ではString型
}
val power: (Int) -> Int = { it * it }
val power: Int => Int = {(it) => it * it}
class MyException(override val message: String): Exception(message)
throw MyException("Hoge")
class MyException(val message: String) extends Exception(message)
throw new MyException("Hoge")
fun foo(): Nothing = TODO()
def foo() = ???
val list = listOf(1, 2, 3)
list.filter{ it > 2 } // [3]
val list = List(1, 2, 3)
list.filter{it => it > 2} // List(3)
val iLtj = if(i < j) "i < j" else "i >= j" // String
val x: Any = "FOO"
x match {
case x:String => // Scalaだと型に対するパターンマッチを使う
}
when(v) {
0 -> ...
1 -> ...
}
v match {
case 0 => ...
case 1 => ...
}
class Person(val name: String, val age: Int)
class Person(val name: String, val age: Int)
data class Person(val name: String, val age: Int)
case class Person(name: String, age: Int)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment