Advertisement
NLinker

Scala type classes, dispatch on return type

May 16th, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.17 KB | None | 0 0
  1. package tt
  2.  
  3. object ChannelTest extends App {
  4.  
  5.   def process[T: Operation](channelId: Long): T = {
  6.     val channel = ChannelService.byId(channelId)
  7.     val op = implicitly[Operation[T]]
  8.     // specific operation depending on concrete T
  9.     val t: T = op.read(channel)
  10.     op.write(channel, t)
  11.     t
  12.   }
  13.  
  14.   import Implicits._
  15.   val x: Int = process[Int](1L)
  16.   val y: String = process[String](2L)
  17. }
  18.  
  19.  
  20. case class Channel(channelId: Long)
  21.  
  22. object ChannelService {
  23.   def byId(channelId: Long) = Channel(channelId)
  24. }
  25.  
  26. trait Operation[T] {
  27.   def read(channel: Channel): T
  28.   def write(channel: Channel, t: T): Unit
  29. }
  30.  
  31. object Implicits {
  32.   implicit val intOp: Operation[Int] = new Operation[Int] {
  33.     def read(channel: Channel): Int = {
  34.       println("intOp.read")
  35.       channel.toString.length
  36.     }
  37.     def write(channel: Channel, t: Int): Unit = {
  38.       println("intOp.write")
  39.     }
  40.   }
  41.  
  42.   implicit val stringOp: Operation[String] = new Operation[String] {
  43.     def read(channel: Channel): String = {
  44.       println("stringOp.read")
  45.       channel.toString
  46.     }
  47.     def write(channel: Channel, t: String): Unit = {
  48.       println("stringOp.write")
  49.     }
  50.   }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement