Skip to content

Instantly share code, notes, and snippets.

@jackywyz
Created September 7, 2011 03:06
Show Gist options
  • Save jackywyz/1199656 to your computer and use it in GitHub Desktop.
Save jackywyz/1199656 to your computer and use it in GitHub Desktop.
scala tips
// scala -P:continuations:enable
//Continuation对于诸如异步I/O,UI事件处理以及数据流并发之类的高级控制建造十分有帮助
import util.continuations._
object Continue{
def say =
reset {
shift {
cf:(Int=>Int) =>
val even = cf(10)
println(even)
val one = cf(100)
println(one)
one
} +1
}
def main(args:Array[String]){
say // output: 11,101
}
}
/**
另外一个例子
**/
import scala.util.continuations._
import java.util.concurrent.Executors
object Test {
val execService = Executors.newFixedThreadPool(2)
def main(args: Array[String]): Unit = {
reset {
val conn = new MyLibraryClient();
conn.connect("127.0.0.1");
println("This will happen after the connection is finished");
}
println("Outside reset");
}
}
class ChannelFuture {
def addListener(listener: ChannelFutureListener): Unit = {
val future = this
Test.execService.submit(new Runnable {
def run(): Unit = {
listener.operationComplete(future)
}
})
}
}
trait ChannelFutureListener {
def operationComplete(f: ChannelFuture): Unit
}
class MyLibraryClient {
def connect(remoteAddr: String): Unit@cps[Unit] = {
shift {
retrn: (Unit => Unit) => {
val future: ChannelFuture = new ChannelFuture()
future.addListener(new ChannelFutureListener {
def operationComplete(f: ChannelFuture): Unit = {
println("operationComplete starts")
retrn();
null
}
});
}
}
}
}
//another example..
import java.net.InetSocketAddress
import java.nio.channels.SelectionKey
import java.nio.channels.Selector
import java.nio.channels.ServerSocketChannel
import java.nio.channels.SocketChannel
import java.nio.ByteBuffer
import scala.collection.JavaConversions.collectionAsScalaIterable
import scala.util.continuations.reset
import scala.util.continuations.shift
import scala.util.continuations.shiftUnit
object Main extends App {
val selector = Selector.open()
val server = ServerSocketChannel.open()
server.socket().bind(new InetSocketAddress(12345))
server.configureBlocking(false)
reset {
while (true) {
server.accept() match {
case c: SocketChannel =>
reset {
println("Accept: " + c)
c.configureBlocking(false)
while (c.isOpen && c.isConnected) {
val bb = ByteBuffer.allocateDirect(1024)
c.read(bb) match {
case count if count > 0 =>
println("Read: " + c + " count: " + count)
bb.flip
while (bb.hasRemaining) {
c.write(bb) match {
case count if count > 0 =>
println("Write: " + c + " count: " + count)
shiftUnit[Unit, Unit, Unit]()
case count if count == 0 =>
println("WriteBlock: " + c)
shift[Unit, Unit, Unit] { cont =>
c.register(selector, SelectionKey.OP_WRITE, cont)
}
case _ =>
println("WriteError: " + c)
bb.clear()
c.close()
shiftUnit[Unit, Unit, Unit]()
}
}
case count if count == 0 =>
println("ReadBlock: " + c)
shift[Unit, Unit, Unit] { cont =>
c.register(selector, SelectionKey.OP_READ, cont)
}
case _ =>
println("ReadError: " + c)
c.close()
shiftUnit[Unit, Unit, Unit]()
}
}
}
shiftUnit[Unit, Unit, Unit]()
case null =>
println("AcceptBlock")
shift[Unit, Unit, Unit] { cont =>
server.register(selector, SelectionKey.OP_ACCEPT, cont)
}
}
shiftUnit[Unit, Unit, Unit]()
}
}
val keys = selector.selectedKeys
while (true) {
selector.select
keys foreach { k =>
k.interestOps(0)
k.attachment.asInstanceOf[Function1[Unit, Unit]].apply(Unit)
}
keys.clear
}
}

####延迟加载

  1. 延迟加载,lazy,只加载一次,然后store

    def say = {println("hello");10}
    lazy val s = say
    println(s)
    println(s)
  2. by-name参数,每次都评估

    def s = {println("hello");2}
    def say(a: =>Int) = println(a+a)
    say(s)

####case class

        case class Person(name: String, age: Int)

        val p = Person("Aaron", 28)
    val name = p.productElement(0) // name = "Aaron": Any
    val age = p.productElement(1) // age = 28: Any
    val fields = p.productIterator.toList // fields = List[Any]("Aaron", 28)

####locally ,代码块

object test {
  object a
  {
    val x = 1
  }

  object b

  { // oops, extra newline disassociates this block with the object b
    val x = 1
  }
}
test.a.x
//test.b.x // doesn't compile
If the programmer really wants that block to stand alone, locally could be used:

object test {
  object a
  {
    val x = 1
  }

  object b

  locally {
    val x = 1
  }
}

####类型参数 ,中缀表示法

   object Main {                                                                   
   class FooBar[A, B]

   def main(args: Array[String]): Unit = {
   var x: FooBar[Int, BigInt] = null
   var y: Int FooBar BigInt   = null
   }
   }

//一些标注 class Foo[@specialized(Int,Boolean) T] //对Int,Boolean类型来说特殊, 节省boxing/unboxing开销。

1. import Predef.{conforms => _, _} //导入Predef除了conforms
2. import java.lang._ ---> import java.lang.{_}
def timed[T](thunk: => T) = {
val t1 = System.nanoTime
val ret = thunk
val time = System.nanoTime - t1
println("Executed in: " + time/1000000.0 + " millisec")
ret
}
//隐式函数和函数作为参数,一举两得。
trait Foo { def bar }
trait Base {
def callBar(implicit foo: Foo) = foo.bar
}
object Test extends Base {
val f: Foo => Unit = { implicit foo =>
callBar
}
def test = f(new Foo {
def bar = println("Hello")
})
}
@throws(classOf[Exception])
final def onReceive(message: Any): Unit = {
message match {
case coordinated @ Coordinated(message) ⇒ {
val others = coordinate(message)
for (sendTo <- others) {
sendTo.actor.tell(coordinated(sendTo.message.getOrElse(message)))
}
before(message)
coordinated.atomic(txFactory) { atomically(message) }
after(message)
}
case message => {
val normal = normally(message)
if (!normal) onReceive(Coordinated(message))
}
}
}
@jackywyz
Copy link
Author

jackywyz commented Sep 7, 2011

scala 向外抛出异常

classOf[T]  类比java中的T.class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment