alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (DirectTypeClassUsage.scala)

This example Scala source code file (DirectTypeClassUsage.scala) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Scala by Example" TM.

Learn more about this Scala project at its project page.

Java - Scala tags/keywords

app, directtypeclassusage, int, intsemigroup, list, none, option, semigroup, some

The DirectTypeClassUsage.scala Scala example source code

package scalaz.example

import scalaz.Semigroup


object DirectTypeClassUsage extends App {

  val o1: Option[Int] = Some(0)
  val o2: Option[Option[Int]] = Some(Some(0))
  val l1: List[String] = List("one")
  val l2: List[List[String]] = List(List("one"))

  direct1()
  direct2()

  // Direct use of type class for one type, Option
  def direct1() {
    import scalaz._

    // Import the members of the type class instance for Option.
    import std.option.optionInstance.{join, bind}

    bind(o1)(x => if (x > 0) Some(2) else None)
    join(o2)
  }


  // Direct use of type class for multiple types
  def direct2() {
    import scalaz._

    // Import the type class instances for Option and List.
    import std.option.{optionInstance, optionMonoid}
    import std.list.listInstance

    optionInstance.bind(o1)(x => if (x > 0) Some(2) else None)
    optionInstance.join(o2)
    listInstance.join(l2)

    implicit object IntSemigroup extends Semigroup[Int] {
      def append(f1: Int, f2: => Int): Int = f1 + f2
    }

    Semigroup[Option[Int]].append(Some(1), None)
  }

}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala DirectTypeClassUsage.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.