Skip to content

Instantly share code, notes, and snippets.

'''
SingleTon class definition
_instance reference of single instance of the class
'''
class SingleTon:
'''
reference to the single instace
'''
_instance = None
@praveenlearning
praveenlearning / ExtensionMethodsInScala3.scala
Created February 21, 2023 15:53
Scala 3 Extension Methods
@main
def main(): Unit =
println(2.square)
// Prints 4 in this example
extension (value: Int)
def square: Int = value * value
@praveenlearning
praveenlearning / ExtensionMethodsInScala2.scala
Last active February 21, 2023 15:34
Scala 2 Extension Methods
object Runner extends App {
// To be imported for implicit context
import Implicits.IntPlus
println(2.square)
// Prints 4 in this example
}
object Implicits {
@praveenlearning
praveenlearning / ConvertCommandLineArgs.scala
Last active February 9, 2023 09:21
Scala 3 introduced main annotation which marks entry to the program. With implementing FromString trait and putting in given clause, command line args can be converted to any type.
import scala.util.CommandLineParser.FromString
given FromString[List[Int]] with
def fromString(s: String): List[Int] = s.split(" ").map(_.toInt).toList
// ex: cmd args = "1 2 3 4 5 6 7 8 9"
@main
def main(numbers: List[Int]): Unit =
println(numbers)
// prints => List(1, 2, 3, 4, 5, 6, 7, 8, 9)
@praveenlearning
praveenlearning / ScalaUnaryMethods.scala
Created February 8, 2023 11:29
Unary methods in scala
// unary methods such as +, -, !, ~ can be achived with defining methods with unary_ as prefix
class Person(name: String):
// definition of unary function
def unary_! : Person =
Person(name.reverse)
override def toString: String = s"Person($name)"
@praveenlearning
praveenlearning / ScalaMethodAssociativity.scala
Last active February 8, 2023 11:20
This code snippet explains how to achieve right associativity in scala
// any method ends with : (colon) will have right assossiative.
// this is only applicable to methods having single argument.
// using scala 3
class Person:
def >>:(any: String) =
println(any)