scala - Implicit conversion not working -
why following implicit method not applied? , how can achieve automatically convert instance of x
instance of y
while having implicit conversion[x,y]
in scope.
trait conversion[x, y] { def apply(x: x): y } implicit object str2intconversion extends conversion[string, int] { def apply(s: string): int = s.size } implicit def convert[x, y](x: x)(implicit c: conversion[x, y]): y = c(x) val s = "hello" val i1: int = convert(s) val i2: int = s // type mismatch; found: string required: int
make conversion extend function1
, don't need helper method anymore:
trait conversion[x, y] extends (x => y) { def apply(x: x): y } // unchanged implicit object str2intconversion extends conversion[string, int] { def apply(s: string): int = s.size } // removed convert // unchanged val s = "hello" val i1: int = convert(s) val i2: int = s
Comments
Post a Comment